dougou8552 2017-03-26 09: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 10: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) {
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部