多维数组按特定ID排序

Multidimensional array sorting by certain ID

我有一个多维数组,如下例所示:

$save[0]['id']='147';
$save[0]['record1']='car';
$save[0]['record2']='road';

$save[1]['id']='147';
$save[1]['record1']='truck';
$save[1]['record2']='wheel';

$save[2]['id']='155';
$save[2]['record1']='cat';
$save[2]['record2']='food';

$save[3]['id']='156';
$save[3]['record1']='baby';
$save[3]['record2']='pacifier';

$save[4]['id']='156';
$save[4]['record1']='mom';
$save[4]['record2']='shirt';

需要这样排序和列出:

  • ID 147:

    • car|road
    • truck|whell
  • ID 155:

    • cat|food
  • ID 156:

    • baby|pacifier
    • mom|shirt

我真的很喜欢这个。谢谢!

基本实现...理论当然是最佳答案;)

<?php

$save[0]['id']=147;
$save[0]['record1']='car';
$save[0]['record2']='road';

$save[1]['id']=147;
$save[1]['record1']='truck';
$save[1]['record2']='wheel';

$save[2]['id']=155;
$save[2]['record1']='cat';
$save[2]['record2']='food';

$save[3]['id']=156;
$save[3]['record1']='baby';
$save[3]['record2']='pacifier';

$save[4]['id']=156;
$save[4]['record1']='mom';
$save[4]['record2']='shirt';


$arr=array();

$i=0;
foreach($save as $k) {
    $i++;
    if(!isset($arr[$k['id']])) {
        $arr[$k['id']]=array();     
    }
    $arr[$k['id']][$i][] = $k['record1'];
    $arr[$k['id']][$i][] = $k['record2'];
}

foreach($arr as $k=>$values) {
    foreach($values as $kk => $v) {
        $arr[$k][$kk] = implode('|', $v);
    }
}

echo "<ul>";
foreach($arr as $id => $values) {
    echo "<li>ID $id</li>";
    if(count($values)) {
        echo "<ul>";
        foreach($values as $value) {
            echo "<li>$value</li>";
        }
        echo "</ul>";
    }
}
echo "</ul>";

echo '<pre>'.print_r($arr,true).'</pre>';

我推荐使用array_multisort。 演示代码:

$array = array(
    array("id" => 115, "record1" => "cat", "food"),
    array("id" => 215, "record1" => "cat2", "food2"),
    array("id" => 22, "record1" => "cat3", "food3")
);

$sort = array();
foreach($array as $key => $value){
    $sort[$key] = $values["id"];
}

array_multisort($sort, SORT_NUMERIC, $array);

var_dump($array);