2013-02-04 32 views
1

我有一個產品陣列,其中包含按其顯示順序排序的產品列表。產品陣列中的一系列類別

$products = array(
[0] = array(
"productID" => 189736, 
"title" => "Spice Girls Album", 
"category" => "CD", 
"order" => "0" 
), 
[1] = array(
"productID" => 23087, 
"title" => "Snakes on a plane", 
"category" => "DVD", 
"order" => "0" 
), 
[2] = array(
"productID" => 9874, 
"title" => "The Beatles Album", 
"category" => "CD", 
"order" => "1" 
), ... etc etc 

我試圖找出邏輯把它變成一個數組類像這樣的:

$categories = array(
    [0] => array(
     "title" => "CD", 
     "products" => array (
      [0] => "Spice Girls Album", 
      [1] => "The Beatles Album" 
     ) 
    ), 
    [1] => array(
     "title" => "DVD", 
     "products" => array (
      [0] => "Snakes on a plane" 
     ) 
) 

因此,對於每一個產品,我有:

if (!in_array($product['cateogry'], $categories)){ 
    $categories[] = $product['cateogry']; 
    $categories[$product['category']][] = $product; 
} else { 
    $categories[$product['category']][]; 
} 

但這ISN不工作,因爲我不認爲in_array正在檢查類別數組的深度。有沒有人有任何建議來解決這個問題的最佳方法?非常感謝

回答

1

您有$categories[$product['category']][] = $product正確的想法一個錯字。你需要檢查什麼是如果存在$categories關鍵$product['category']

if (array_key_exists($product['category'], $categories)) { 
    $categories[$product['category']]['products'][] = $product['title']; 
} else { 
    // initialize category data with first product 
    $categories[$product['category']] = array(
     'title' => $product['category'], 
     'products' => array($product) 
    ); 
} 

這會給你在表單中的數組:

$categories = array(
    "CD" => array(
     "title" => "CD", 
     "products" => array (
      [0] => "Spice Girls Album", 
      [1] => "The Beatles Album" 
     ) 
    ), 
    "DVD" => array(
     "title" => "DVD", 
     "products" => array (
      [0] => "Snakes on a plane" 
     ) 
) 
+0

完美,謝謝。 – Lars

0
$categories = array(); 
foreach($products as $product){ 
    $categories[$product['category']]['title']       = $product['category']; 
    $categories[$product['category']]['products'][$product['productID']] = $product['title']; 
} 

print_r($categories); 
+0

對不起有一個問題,我編輯了代碼:D –

+0

'$ categories [$ product ['category']] ['products'] $ product [['productID']] = $ product ['title']; '應該是'$ categories [$ product ['category']] ['products'] [$ product ['productID']] = $ product ['title'];' –

+0

是的,我編輯它,謝謝:) –

0

你可以使用這樣的事情:

$new_products = array(); 
foreach ($products as $product) { 
    $new_products[$product['category']][] = $product['title']; 
} 

這會把它們放到你想要的數組中。

0
<pre> 
<?php 
$p[] = array(productID => 189736,title => 'Spice Girls Album', category => 'CD', order => 0); 
$p[] = array(productID => 23087, title => 'Snakes on a plane', category => 'DVD', order => 0); 
$p[] = array(productID => 9874, title => 'The Beatles Album', category => 'CD', order => 1); 
foreach($p as $p){ 
    $c[$p['category']]['title'] = $p['category']; 
    $c[$p['category']]['products'][] = $p['title']; 
} 
print_r($c); 
?>