Search code examples
phparraysarray-push

Create Multidimensional Array


I have a function that is currently echoing image urls..

<?php
    $media = get_attached_media( 'image' );
        foreach ($media as $medias)
            {
                echo $medias->guid;
            }
?>

Which gives me the following output...

www.example.com/image1.jpg
www.example.com/image2.jpg
www.example.com/image3.jpg
www.example.com/image4.jpg

I am trying to put this data into a multi-dimensional array in a function instead that looks like this...

<?php
$images = serialize( array(
    'docs' => array(
        array( 'property_imgurl' => 'http://wwww.mydomain.com/image1.jpg' ),
        array( 'property_imgurl' => 'http://wwww.mydomain.com/image2.jpg' ),
    ) )
);

print_r( $images );

?>

I have read up on array_push, is this what I should be using or is it simpler than this?


Solution

  • Try using the $docs[] operator/shorthand:

    <?php
        $docs = array();
        $media = get_attached_media('image');
        foreach($media as $medias) {
            $docs[] = $medias->guid;
        }
        $images = seralize(array('docs' => $docs));
        print_r($images);
    ?>
    

    It's just short hand for array_push see the php.net docs:

    http://php.net/manual/en/function.array-push.php

    Cheers!