2017-03-26 69 views
-1

我正在使用PHP和多維數組。我已經將點和其他信息存儲爲字符串變量。在我的數組中使用字符串變量非常重要。PHP排序多維數組並添加新項目

我想排序數組並添加3個新項目。我應該能夠對我的子陣列進行排序。我也應該能夠排序我的點(pts_sting)和比賽(c_string)的字符串變量。

我需要某種foreach循環來自動完成這項工作。

也許下面的例子比我的話更有幫助。

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 
    ) 
) 
) 

結果應該是這樣的:

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 
    ) 
) 
) 
+0

可能的重複[如何在PHP中對數組和數據進行排序?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – zett42

回答

0

你可以這樣做:

$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); 

如果你有這樣做的陣列中的每個項目,把所有的代碼在foreach循環中並用$item替換$arr["25"]

foreach ($arr as &$item) { 
    ... 
} 
+0

謝謝,看起來不錯。如果我不知道這個子數組是[25],我怎麼能修改代碼?子數組幾乎可以是任何東西。 – xms

+0

因此,如果我有幾個子數組,那麼讓我們說[20],[23]和[25],foreach循環是否會遍歷所有這些子數組? – xms

+0

uasort row給我:警告:非法字符串偏移量...怎麼辦? – xms