Black
Black

Reputation: 20232

Output multidimensional array with keys and values

I have an array ($myarray), i try to output each element in a foreach loop with it's keys and values, but i don't know how. The following array is the result of a parsed .ini file. This is the output of print_r($myarray);

Array
(
    [Array1] => Array ( [A] => Test [B] => 123 )
    [Array2] => Array ( [C] => Test [D] => 123 )
    [Array3] => Array ( [E] => Test [F] => 123 )
)

I tried it like this:

foreach ($myarray as $x)
{
    echo "<p>".$x." ";

    foreach($x as $key => $value)
    {
        echo $key." = ".$value . ";";

    }
    echo "</p>";
}

I expect something like this:

Array1:  A = Test; B = 123
Array2:  C = Test; D = 123
Array3:  E = Test; F = 123

But unfortunattely i get no output. I obviouisly misunderstood something.

Upvotes: 1

Views: 3782

Answers (3)

Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

Or you can just use:

echo '<pre>';
echo print_r($myarray, true); // this will return the output, not echo it
echo '</pre>';

Or

echo '<pre>';
print_r($myarray); // this echo it, but after <pre> and before </pre>
echo '</pre>';

Or write a recursive function:

function output_myarray($myarray) {
    $output = array();

    foreach($myarray as $key => $value) {
        if(is_array($value)) {
            $output[] = output_myarray($value);
        } else {
            $output[] = '<p>' . $key . ' = ' . $value . ';';
        }
    }

    return $output;
}

And echo it:

echo '<pre>';
echo print_r(output_myarray($myarray), true);
echo '</pre>';

Or even simplier:

echo implode('', output_myarray($myarray), true);

Or by new line:

echo implode("\n", output_myarray($myarray), true);

Upvotes: 1

Dave
Dave

Reputation: 3288

Your code seems to work almost fine only difference is you're not defining the key/value pair for the master array so you're expecting to get a key back from an array() which will return $x as array() or nothing when output

    $myarray = array(
            "Array1" =>array("A" => "Test", "B" => 123),
            "Array2" =>array("C" => "Test", "D" => 123),
            "Array3" =>array("E" => "Test", "F" => 123)
            );
foreach ($myarray as $masterkey => $mastervalue)
{
    echo "<p>".$masterkey." ";

    foreach($mastervalue as $key => $value)
    {
        echo $key." = ".$value . ";";

    }
    echo "</p>";
}

This is the example code I used (based off yours)

outputs

Array1 A = Test;B = 123;

Array2 C = Test;D = 123;

Array3 E = Test;F = 123;

Upvotes: 4

timclutton
timclutton

Reputation: 13004

Your inner foreach is correct in that you assign the key and the value to variables via the $key => $value syntax. You need to do the same thing in your outer loop:

foreach ($myarray as $x => $y)
{
    echo "<p>".$x." ";

    foreach($y as $key => $value)
    {
        echo $key." = ".$value . ";";

    }
    echo "</p>";
}

Upvotes: 2

Related Questions