2017-10-11 66 views
0

我有此數組:PHP排序多維數組失敗

Array 
(
    [0] => Array 
     (
      [id] => 83 
      [value] => Figures 
     ) 

    [1] => Array 
     (
      [id] => 85 
      [value] => Toys 
     ) 

    [2] => Array 
     (
      [id] => 36 
      [value] => Nintendo Switch 
     ) 

) 

,我有這樣的代碼進行排序基於id數組:

function cmp($a, $b) { 
    return strcmp($a->id, $b->id); 
} 

while ($row = $result->fetch_assoc()) { 

    $category = json_decode($row['product_cat'], true); 

    usort($category, "cmp"); 

    echo '<pre>'; 
    print_r($category); 
    echo '</pre>'; 
} 

如我所料的結果是不工作的,因爲id=85前置於id=83

Array 
(
    [0] => Array 
     (
      [id] => 36 
      [value] => Nintendo Switch 
     ) 

    [1] => Array 
     (
      [id] => 85 
      [value] => Toys 
     ) 

    [2] => Array 
     (
      [id] => 83 
      [value] => Figures 
     ) 

) 

爲什麼PHP成功地將id=36作爲第一個數組的值,但未能進行排序id=85id=83

謝謝。

+1

的strcmp($ A [ '身份證'],$ B [ '身份證']),是你使用數組? – tan

回答

2

變化

return strcmp($a->id, $b->id); 

return strcmp($a['id'], $b['id']); 
1

您可以使用這樣

$mylist = array(array("id"=>83,"value"=>"Figures"),array("id"=>85,"value"=>"Toys"),array("id"=>36,"value"=>"Nintendo Switch")); 

echo "<pre>"; 

$sort = array(); 
foreach($mylist as $k=>$v) { 
    $sort['id'][$k] = $v['id']; 
    $sort['value'][$k] = $v['value']; 
} 
# sort by event_type desc and then title asc 
array_multisort($sort['id'], SORT_ASC, $sort['value'], SORT_ASC,$mylist); 

print_r($mylist); 

並獲得輸出像下面

Array 
(
    [0] => Array 
     (
      [id] => 36 
      [value] => Nintendo Switch 
     ) 

    [1] => Array 
     (
      [id] => 83 
      [value] => Figures 
     ) 

    [2] => Array 
     (
      [id] => 85 
      [value] => Toys 
     ) 

) 
0
$category = array ([ 
     'id' => 36, 
     'value' => 'Nintendo Switch' 
], [ 
     'id' => 85, 
     'value' => 'Toys' 
], [ 
     'id' => 83, 
     'value' => 'Figures' 
]); 

$sortArry = []; 
foreach ($category as $c) { 
    $sortArry[$c['id']] = $c; 
} 

echo '<pre>'; 
print_r($sortArry); 
array_multisort($sortArry); 
print_r($sortArry); 
exit; 

將ID置於陣列中,然後使用multisort。它會工作。

0

這僅僅是一個內襯

array_multisort(array_column($yourArray, "id"), SORT_ASC, $yourArray); 

你可以在這裏找到它,以及:http://php.net/manual/en/function.array-multisort.php

搜索該手冊頁的「array_column」。

我用這個來測試:

$yourArray = array (
"0" => Array 
    (
     "id" => 83, 
     "value" => "Figures" 
    ), 
"1" => Array 
    (
     "id" => 85, 
     "value" => "Toys" 
    ), 
"2" => Array 
    (
     "id" => 36, 
     "value" => "Nintendo Switch" 
    ) 
); 

array_multisort(array_column($yourArray, "id"), SORT_ASC, $yourArray); 
print_r($yourArray); 

,結果是這樣的:

Array ([0] => Array ([id] => 36 [value] => Nintendo Switch) 
     [1] => Array ([id] => 83 [value] => Figures) 
     [2] => Array ([id] => 85 [value] => Toys))