dougou8552 2017-03-26 17:56
浏览 25
已采纳

PHP排序多维数组并添加新项

I am using PHP and a multidimensional array. I have stored points and other information as string variables. It is very important that I use string variables in my array.

I would like to sort the array and add 3 new items. I should be able to sort my subarrays. I also should be able to sort my string variables of points (pts_sting) and competitions (c_string).

I need some kind of foreach loop to do the job automatically.

Maybe the following example helps more than my words.

Array (
  [25] => Array (
    [1] => Array (
      [pts_string] => 00450
      [c_string] => 00011
    )

    [2] => Array (
      [pts_string] => 00600
      [c_string] => 00025
    )

    [3] => Array (
      [pts_string] => 00375
      [c_string] => 00033
    )
  )
)

The result should look like this:

Array (
  [25] => Array (
    [pts_total] = 1425 /* 600 + 450 + 375 */
    [all_pts_strings] = 00600 00450 00375 /* biggest points, 2nd biggest, etc. */
    [all_c_strings] = 00025 00011 00033 /* competition of biggest points, 2nd biggest, etc. */
    [no_of_competitions] = 3 /* [1], [2], and [3] = 3 in total */

/* biggest points first... */

    [2] => Array (
      [pts_string] => 00600
      [c_string] => 00025
    )

/* 2nd biggest points... */

    [1] => Array (
      [pts_string] => 00450
      [c_string] => 00011
    )

/* 3rd biggest points... */

    [3] => Array (
      [pts_string] => 00375
      [c_string] => 00033
    )
  )
)
  • 写回答

1条回答 默认 最新

  • duanlachu7344 2017-03-26 18:17
    关注

    You can do that:

    $arr = [
        "25" => [
            "1" => ["pts_string" => "00450", "c_string" => "00011"],
            "2" => ["pts_string" => "00600", "c_string" => "00025"],
            "3" => ["pts_string" => "00375", "c_string" => "00033"]
        ]
    ];
    
    uasort($arr["25"], function ($a, $b) { return $b['pts_string'] - $a['pts_string']; }); 
    
    $pts = array_column($arr["25"], "pts_string");
    $c = array_column($arr["25"], "c_string");
    
    $arr["25"] = [ "pts_total" => array_sum($pts),
                   "all_pts_strings" => implode(' ', $pts),
                   "all_c_strings" => implode(' ', $c),
                   "no_of_competitions" => count($arr["25"])
                 ] + $arr["25"];
    
    print_r($arr);
    

    If you have to do it for each item in the array, put all the code in a foreach loop and replace $arr["25"] with $item:

    foreach ($arr as &$item) {
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图