0

Not sure what I'm doing wrong with this one, but when I attempt to do a foreach loop with a variable, it comes back with Array Array.

PHP Code:

  <?php foreach ($thing as $t) : ?>
    <?php $thisStuff = $t[stuff];  ?>
    <?php echo $thisStuff; ?>
  <?php endforeach; ?>

Output: Array Array

Could this be possibly that there is another array within $thisStuff? If so would I loop through that data?

ultraloveninja
  • 1,969
  • 5
  • 27
  • 56

2 Answers2

1

If you have a multidimensional array you'll need to use a recursive function.

an example might be this

function unfoldArray($array,$output = array()) {
    if(is_object($array)) {
        $array = (array)$array;
    }
    foreach($array as $key => $value) {
        if(is_array($value) || is_object($value)) {
            //$output[] = $key;
            $output = unfoldArray($value,$output);
        } else {
            $output[] = $value;
        }
    }
    return $output;
}

the above function, given an array like

$array = array(
    "one",
    "two",
    "three" => array("A","B","C"),
    "four" => array("X","Y","Z"),
    "five",
    "six" => array(
        "sub_one",
        "sub_two",
        "sub_three" => array("sub_A","sub_B","sub_C")
    ),
    "seven"
);
$output = unfoldArray($array);

would return a flat array like this

   // $output 
   [
        "one",
        "two",
        "A",
        "B",
        "C",
        "X",
        "Y",
        "Z",
        "five",
        "sub_one",
        "sub_two",
        "sub_A",
        "sub_B",
        "sub_C",
        "seven"
    ]

you may notice that values "three" and "six" are omitted from the result array because they are key, but if you wan to include them just uncomment the line //$output[] = $key; in the function.

Once you have this array you may just loop with a foreach. This might not be exactly what you need, but should give you a direction to follow.

Igor S Om
  • 735
  • 3
  • 12
  • Awesome, thanks! Yeah, I was messing around with nesting a `foreach` loop in another `foreach` loop and while I'm getting the results it just seems really messy. – ultraloveninja Aug 15 '17 at 01:18
0

Try with key => value method:

  <?php foreach ($thing as $key => $value) : ?>
    // if $value is array, you need to iterate it the same way (additional foreach)
    <?php echo $value; ?>
  <?php endforeach; ?>
mitch
  • 2,235
  • 3
  • 27
  • 46