Snappysites Snappysites - 2 months ago 8
PHP Question

Foreach on array with combined keys

I am trying to loop through this array and echo results accordingly, my array displays like this at the moment:

Array (
[2016 Q1] => 692.00
[2016 Q2] =>
Array (
[0] => 809.00
[1] => 1.00
)
[2016 Q3] =>
Array (
[0] => 290.00
[1] => 8.00
[2] => 2.50
)
)


I need it to show something like this:

2016 Q1
692.00
2016 Q2
809.00
1.00
2016 Q3
290.00
8.00
2.50


Although at the moment it shows like this:

2016 Q1
692.00
2016 Q2
Array
2016 Q3
Array


Here is my current script:

$result = array_merge_recursive($quarter_invoice, $quarter_ads, $quarter_account);

foreach ($result as $key => $value){
echo $key.'<br>';
echo $value.'<br>';
}


How do I access the second lot of Arrays to display?

Answer

You first element is not an array, but a float/ single value. Your next two elements are both arrays. You need to have more consistency. I assume your first element should be in an array? like this ?

Array (
    [2016 Q1] => 
      Array (
        [0] => 692.00
    )
    [2016 Q2] =>
    Array (
        [0] => 809.00
        [1] => 1.00
    )
    [2016 Q3] =>
    Array (
        [0] => 290.00
        [1] => 8.00
        [2] => 2.50
    )
)

then your script can look like this

$result = array_merge_recursive($quarter_invoice, $quarter_ads, $quarter_account);

foreach ($result as $key => $value){
    echo $key."<br>";
    foreach($value as $element){
        echo $element."<br>;
    }
     echo "<br>";
}

if i am wrong, and you do need that exact structure you mention orginally. Do something like this

$result = array_merge_recursive($quarter_invoice, $quarter_ads, $quarter_account);

foreach ($result as $key => $value){
    echo $key."<br>";
    if(is_array($value)){
        foreach($value as $element){
             echo $element."<br>;
         }
     }else{
       echo $value;
     }
     echo "<br>";
}

This may seem inefficient just for outputting (could just implode), but I assume you need to do more than just output when iterating and manipulating these different types.