PHP - 嵌套foreach循环中多维数组键的字符串值

时间:2018-01-06 18:58:00

标签: php arrays multidimensional-array foreach

我正在尝试获取最内层数组的键的字符串值但是,Food & DrinkCandy& Tea or Coffee Sets只需返回Array

<?php

$categoryParents = array(

  'Food & Drink' => array(
      'Beverages' => array(
        'Energy & Sports Drinks',
        'Wine & Champagne'
      ),
      'Candy' => array(
        'Chewing Gum',
        'Lollipops',
        'Jelly Beans'
      ),
      'Candy Dishes',
      'Food Gifts',
      'Fruit',
      'Popcorn',
      'Pretzels',
      'Seeds',
      'Spices',
      'Tea Or Coffee Sets' => array(
        'Coffee',
        'Tea'
      ),
      'Water'
  )

);

foreach ($categoryParents as $pcat => $psubcats) {
  foreach ($psubcats as $psubcat) {
    if (is_array($psubcat) && sizeof($psubcat) > 0) {
      print_r($psubcat . " <-- parent test \n");
      foreach ($psubcat as $psub2cat) {
        print_r($psub2cat . " <-- sub \n");
      }
    } else {
      print_r($psubcat . "<-- parent \n");
    }
  }
}

?>

我机器上此脚本的输出如下:

PHP Notice:  Array to string conversion in /Users/guy/Desktop/test-2.php on line 34

Notice: Array to string conversion in /Users/guy/Desktop/test-2.php on line 34
Array <-- parent test 
Energy & Sports Drinks <-- sub 
Wine & Champagne <-- sub 
PHP Notice:  Array to string conversion in /Users/guy/Desktop/test-2.php on line 34

Notice: Array to string conversion in /Users/guy/Desktop/test-2.php on line 34
Array <-- parent test 
Chewing Gum <-- sub 
Lollipops <-- sub 
Jelly Beans <-- sub 
Candy Dishes<-- parent 
Food Gifts<-- parent 
Fruit<-- parent 
Popcorn<-- parent 
Pretzels<-- parent 
Seeds<-- parent 
Spices<-- parent 
PHP Notice:  Array to string conversion in /Users/guy/Desktop/test-2.php on line 34

Notice: Array to string conversion in /Users/guy/Desktop/test-2.php on line 34
Array <-- parent test 
Coffee <-- sub 
Tea <-- sub 
Water<-- parent 

这就像我让这个脚本工作一样接近。我很确定我在嵌套的foreach循环中缺少一大块条件逻辑,我再也无法思考了。任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:1)

将此片段写入以打印数组键

foreach ($psubcats as $k => $psubcat) {
    if (is_array($psubcat) && sizeof($psubcat) > 0) {
      print_r($k . " <-- parent test \n");

demo