0

I'm trying to get the string value of the key of the innermost array(s) However, Food & Drink, Candy & Tea or Coffee Sets just return as 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");
    }
  }
}

?>

The Output of this script on my machine is as follows:

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 

This is as close as I've gotten this script to work. I'm pretty sure I'm missing a chunk of conditional logic in the nested foreach loops, I just can't think through it anymore. Any guidance would be appreciated.

1 Answer 1

1

Write this fragment so to print array key

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

demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.