2016-05-15 68 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

我看,它类似于我所寻找的,但不是确切的。我正在查找每个类别的列表,而不重复它们,并且处于同一级别的数组中,因此我可以使用它们作为菜单。我可能没有解释我的自我,但非常感谢! –