2014-09-25 78 views
0

所以我有一個數組象下面這樣:如何基於數組中的值顯示數組列表?

Array 
(
[0] => Array 
    (
     [model] => COROLLA 
     [trim] => L 
     [msrp] => 16,800 
     [type] => car 
    ) 

[1] => Array 
    (
     [model] => COROLLA 
     [trim] => LE 
     [msrp] => 18,300 
     [type] => car 
    ) 

我需要能夠調用類型的所有獨特的價值觀和遍歷它們將其返回彷彿類型爲一類。所以,我需要讓所有的車「作爲一種類型另一份與「範」的所有車輛的類型等車輛我這得到唯一值的列表:

$type = array(); 
    foreach($cars as $car){ 
    $type[] = $car['type']; 
    } 
$type = array_unique($type); 

我如何搜索它們的值並返回頂層數組真的遇到了一堵牆。我知道這是基本的,但我很掙扎。

+1

可否請你改一下你想要什麼? (例如,提供示例輸出將有很大幫助) – bwoebi 2014-09-25 22:01:33

+0

也可以查看http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – 2014-09-25 22:18:03

回答

2

下面的代碼將導致一個陣列組的車輛按類型:

$vbt = array(); 
foreach ($cars as $car) 
{ 
    $vbt[ $car['type'] ][] = $car; 
} 

所以,現在你有一個數組,看起來像這樣:

/* 
$vbt == Array 
(
    [car] => Array 
    (
     [0] => Array 
     (
      [model] => COROLLA 
      [trim] => L 
      [msrp] => 16,800 
      [type] => car 
     ) 

     [1] => Array 
     (
      [model] => COROLLA 
      [trim] => LE 
      [msrp] => 18,300 
      [type] => car 
     ) 
    ) 

    [van] => Array 
    (
     [0] => Array 
     (
      [model] => ODYSSEY 
      [trim] => L 
      [msrp] => 16,800 
      [type] => van 
     ) 
    ) 
) 
*/ 

從這個結構,你可以訪問任何如果您有類型的車輛列表,例如,獲得所有type == van您將要做的排列:

$vans = $vbt['van']; 

/* 
$vans == Array 
(
    [0] => Array 
    (
     [model] => ODYSSEY 
     [trim] => L 
     [msrp] => 16,800 
     [type] => van 
    ) 
) 
*/ 

如果你已經知道的類型,你只是想獲得該類型的車輛的清單:

$vehicles = array(); 
$searchType = 'car'; 
foreach ($cars as $car) 
{ 
    if ($car['type'] == $searchType) 
    { 
     $vehicles[] = $car; 
    } 
} 


/* 
$vehicles == Array 
    (
     [0] => Array 
     (
      [model] => COROLLA 
      [trim] => L 
      [msrp] => 16,800 
      [type] => car 
     ) 

     [1] => Array 
     (
      [model] => COROLLA 
      [trim] => LE 
      [msrp] => 18,300 
      [type] => car 
     ) 
    ) 
*/ 
0

如果你有PHP> = 5.5.0你可以用自己的鑰匙這樣的關聯的類型:

$cars_types = array_column($cars, 'type'); 

然後,你可以排序的類型和循環它訪問$cars陣列:

asort($cars_types); 

foreach($cars_types as $key => $type) { 
    echo $type; // or $cars[$key]['type'] 
    echo $cars[$key]['model']; 
    //etc 
}