2016-08-02 57 views
-3

我在這陣混亂的點點..如何創建逗號從嵌套數組分隔列表中的PHP

其實我有這樣的

Array 
(
    [0] => stdClass Object 
     (
      [restaurant_id] => 1 
      [food_item] => Chicken Spicy Pizza 
     ) 

    [1] => stdClass Object 
     (
      [restaurant_id] => 1 
      [food_item] => Pepper Chicken Sandwich 
     ) 

    [2] => stdClass Object 
     (
      [restaurant_id] => 6 
      [food_item] => Chicken Tikka Roll 
     ) 

    [3] => stdClass Object 
     (
      [restaurant_id] => 6 
      [food_item] => Grilled Chicken 
     ) 

) 

在這裏,我需要一個數組創建的food_item逗號分隔值,並且還必須有一個條件具有相同restaurant_id也合併數組..

即; ..

我的鰭人陣應該是這樣..

Array 
(
    [0] => stdClass Object 
     (
      [restaurant_id] => 1 
      [food_item] => Chicken Spicy Pizza,Pepper Chicken Sandwich 
     ) 

    [1] => stdClass Object 
     (
      [restaurant_id] => 6 
      [food_item] => Chicken Tikka Roll,Grilled Chicken 
     ) 
) 

什麼建議?!! ...

謝謝!

+0

什麼你試過嗎?建議根據您的嘗試。 –

回答

2

您可以使用array_reduce來完成它

$myArr = array_reduce($myArr, function ($carry, $item) { 
    if (!isset($carry[$item->restaurant_id])) { 
     $carry[$item->restaurant_id] = $item; 
    } else { 
     $carry[$item->restaurant_id]->food_item .= ',' . $item->food_item; 
    } 
    return $carry; 
}, array()); 
+1

謝謝Matei Mihai對你的建議 –

2

讓您的實際數組存在一個名爲$actualArr的變量中。因此,這裏的代碼

 $actualArr = array(
     (object) array('restaurant_id' => 1, 'food_item' => 'Chicken Spicy Pizza'), 
     (object) array('restaurant_id' => 1, 'food_item' => 'Pepper Chicken Sandwich'), 
     (object) array('restaurant_id' => 6, 'food_item' => 'Chicken Tikka Roll'), 
     (object) array('restaurant_id' => 6, 'food_item' => 'Grilled Chicken'), 
    ); 



$newArr = array(); 
foreach($actualArr as $value){ 
    $newArr[$value->restaurant_id][] = $value->food_item; 
} 

$finalArr = array(); 

foreach($newArr as $key => $value){ 
    $finalArr[] = (object) array('restaurant_id' => $key, 'food_item' => implode(',', $value)); 
} 
echo '<pre>'; 
print_r($finalArr); 

下面是代碼鏈接

http://pastebin.com/RvjQ3Edj

+0

@ Md。Sahadat Hossain非常感謝你,我終於明白了.. :) –

相關問題