按特定ID排序的多维数组

时间:2015-01-21 13:02:53

标签: php arrays sorting multidimensional-array

我有一个多维数组,看起来像这个例子:

$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:

         
        
    • 汽车|公路
    •   
    • 卡车|喂线轮
    •   
  •   
  • ID 155:

         
        
    • 猫|食品
    •   
  •   
  • ID 156:

         
        
    • 婴儿|奶嘴
    •   
    • 妈妈|衬衫
    •   
  •   

我真的堆叠在这上面。谢谢!

2 个答案:

答案 0 :(得分:1)

基本实现......当然有最佳答案;)

<?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>';

答案 1 :(得分:0)

我建议使用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);