2016-05-15 71 views
1

下面是數組的代碼。我試圖列出內部數組中的字段類別,並且當該字段爲空時寫入「無類別」。而我根本做不到。我一直試圖用兩個foreach嵌套將列表保存到一個新的數組中,但我不能完全正確地使用它。如何從3D數組內部數據中創建列表PHP

 Array(
'type' => 'success', 
'value => array (
    0 => array (
     'id' => 1, 
     'joke' => 'Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.', 
      'categories' => array()); 
    1 => array (
      'id' => 2, 
      'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.', 
      'categories' => array(    
      [0] => nerdy       
      )); 
     2 => array (
      'id' => 3, 
      'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.', 
      'categories' => array(    
      [0] => explicit 
      )); 
    ); 
) 

//這是我想沒有運氣

$output = array(); 

    foreach($response as $row){ 
     foreach($row as $cat){ 
      $output[] = $cat['categories']; 
     } 
    } 

謝謝!

+0

你想做什麼,如果它是空的?在'$ output'中添加「無類別」或回顯這個文本? – olibiaz

+0

是的,我可以,但我只想添加「無類別」和所有其他類別只有一次... –

回答

0

首先,數組中有錯誤的語法,分號代替逗號和方括號中的數組鍵。這是正確的語法。

$response = Array(
    'type' => 'success', 
    'value' => array (
     0 => array ('id' => 1, 'joke' => 'Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.', 'categories' => array()), 
     1 => array ('id' => 2, 'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.', 
      'categories' => array(0 => 'nerdy')), 
     2 => array (
      'id' => 3, 
      'joke' => 'MacGyver can build an airplane out of gum and paper clips. Chuck Norris can kill him and take it.', 
      'categories' => array(
      0 => 'explicit')))); 

現在輸出。你想要一個輸出,其中'沒有類別'字段將是一個字符串,對不對?所以結果數組的print_r看起來像這樣。

Array 
(
    [0] => without category 
    [1] => Array 
     (
      [0] => nerdy 
     ) 

    [2] => Array 
     (
      [0] => explicit 
     ) 

) 

如果是的話,這裏是你如何解開你的數組。

foreach($response as $row) { 
    if (is_array($row)) { 
     foreach($row as $cat) { 
      if (empty($cat['categories'])) { 
       $output[] = 'without category'; 
      } else { 
       $output[] = $cat['categories']; 
      } 
     } 
    } 
} 
+0

我看,它類似於我所尋找的,但不是確切的。我正在查找每個類別的列表,而不重複它們,並且處於同一級別的數組中,因此我可以使用它們作爲菜單。我可能沒有解釋我的自我,但非常感謝! –