0

I have a php array object $images if I print this array by print_r($images), I gets following structure.

Array
(
    [0] => stdClass Object
        (
            [image_name] => 1.jpg
        )

    [1] => stdClass Object
        (
            [image_name] => 2.jpg
        )

    [2] => stdClass Object
        (
            [image_name] => 3.jpg
        )
)

and I want to convert its structure as;

Array
(
    [image_name] => stdClass Object
        (
            [0] => 1.jpg
            [1] => 2.jpg
            [2] => 3.jpg
        )
)

Some one please suggest me a function to do that in php.

5
  • Is it always going to have the same format? Commented Feb 26, 2016 at 14:44
  • yes, I will get only the specified format. Commented Feb 26, 2016 at 14:45
  • 4
    Why should it output an array with an object inside? Are you sure it should not just be an array? Commented Feb 26, 2016 at 14:46
  • I used print_r() to output it. Commented Feb 26, 2016 at 14:52
  • I think @SverriM.Olsen asked you you want output as stdClass Object normally array is used, just to clarify if it was a mistake. Commented Feb 26, 2016 at 15:02

1 Answer 1

3

You can do a simple loop.

$imagesArray = ['image_name' => new \stdClass()];
$counter = 0;
foreach ($images as $image) {
    $imagesArray['image_name']->$counter = $image->image_name;
    $counter++;
}

Explanation

I've first created an array $imagesArray with one element of stdClass, then I put the image_name as key. Then by using foreach loop of array of images $images, every $image is stdClass object, you just get the image_name property and assign it to the image_name object as $counter, which is just an integer.

Sign up to request clarification or add additional context in comments.

6 Comments

$imagesArray will be an array not object
@VasilShaddix Yeah, its working. What you did? I mean Can you explain it. Thanx.
perfect! one trick: $imagesArray['image_name']->{$counter++} = $image->image_name; instead of 2 lines :)
@VasilShaddix, Now it is a good answer, some comment/explanation will make it great.
You create an array with one element of stdClass, i put the 'image_name' as key. Then you use foreach to loop through your array of images. Every $image is stdClass object, you just get the image_name property and assign it to the image_name object as $counter, which is just an integer.I wouldn't use such structure as @bansi suggested. Hope you could understand it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.