Question

I'm trying to output values from a multiarray with PHP, but I can't get my head around on how to retrieve a specific value from each entry.

Array -

Array
(
    [images] => Array
        (
            [0] => Array
                (
                    [image] => sample1.jpg
                )

                [1] => Array
                    (
                        [image] => sample2.jpg
                    )

            )

    )

Code -

if ($query) {
    foreach ( $query as $outer_array ) {
        foreach ( $outer_array as $inner_array ) {
            $html .= '<img src="' . $inner_array[image] . '" alt="" />';
        }
    }
}

Current output -

<img src="" alt="" />
<img src="" alt="" />

This gives me blank weird results. Tried a dozen different approaches, I guess I'm just not well enough proficient in how multiarrays work.

Edit: Went with another approach. Thanks for all the help!

Was it helpful?

Solution 2

If your structure is like in your example you can save one of the loops by directly looping over $query['images']:

if (!empty($query['images'])) {
    foreach((array) $query['images'] as $image) {
        $html .= '<img src="' . $image['image'] . '" alt="" />';
    }
}

OTHER TIPS

put quotes around image first :

$inner_array['image']

if $query represents the outer most array then you just need to change

foreach ( $query as $outer_array )

to

foreach ( $query['images'] as $outer_array )

so it should look like:

    if (isset($query['images']) && is_array($query['images'])) {

    foreach ( $query['images'] as $inner_array ) {            

            $html .= '<img src="' . $inner_array['image'] . '" alt="" />';

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top