0

I have this array of object and I need to remove the key "0" :

 "images": [
        {
            "0": "http://example.test/uploads/products/jqGfPyIUc_Wd.jpg"
        },
        {
            "0": "http://example.test/uploads/products/bC1UIM5WwT8f.jpeg"
        }
    ],

my code:

'images' => $this->images->map(function($item){ 

      return (object)[$item->image_path];

 }),

I need to remove the keys and keep it as an array like this:

 "images": [
        {
            "http://example.test/uploads/products/jqGfPyIUc_Wd.jpg"
        },
        {
            "http://example.test/uploads/products/bC1UIM5WwT8f.jpeg"
        }
    ],

2 Answers 2

2

Object properties should always have a key. if you do not want it to have a key then you should store it as a nested array instead:

'images' => $this->images->map(function($item){ 
      return array($item->image_path);
 }),

// will create:

 "images": [
        [
            "http://example.test/uploads/products/jqGfPyIUc_Wd.jpg"
        ],
        [
            "http://example.test/uploads/products/bC1UIM5WwT8f.jpeg"
        ]
    ],

or just map it to string values and keep it as a standard array:

'images' => $this->images->map(function($item){ 
      return $item->image_path;
 }),

// will create:

 "images": [
        "http://example.test/uploads/products/jqGfPyIUc_Wd.jpg",
        "http://example.test/uploads/products/bC1UIM5WwT8f.jpeg"
    ],
Sign up to request clarification or add additional context in comments.

Comments

0

That array looks like javascript. If it is, you can map it out as follows.

console.log(images);
/*
[
    {'0': 'http://example.test/uploads/products/jqGfPyIUc_Wd.jpg'},
    {'0': 'http://example.test/uploads/products/bC1UIM5WwT8f.jpeg'}
]
*/
console.log(images.map(value => value[0]));
/*
[
    'http://example.test/uploads/products/jqGfPyIUc_Wd.jpg',
    'http://example.test/uploads/products/bC1UIM5WwT8f.jpeg'
]
*/

If it's a php array, it looks like it came from a json_decode call. You can map it.

var_dump($images)
/*
[
    {#3145
        +"0": "http://example.test/uploads/products/jqGfPyIUc_Wd.jpg",
    },
    {#3142
        +"0": "http://example.test/uploads/products/bC1UIM5WwT8f.jpeg",
    },
]
*/
var_dump(array_map(function($value) { return $value->{'0'}; }, $images));
/*
[
    'http://example.test/uploads/products/jqGfPyIUc_Wd.jpg',
    'http://example.test/uploads/products/bC1UIM5WwT8f.jpeg'
]
*/
# PHP >= 7.4
var_dump(array_map(fn($value) => $value->{'0'}, $images));
/*
[
    'http://example.test/uploads/products/jqGfPyIUc_Wd.jpg',
    'http://example.test/uploads/products/bC1UIM5WwT8f.jpeg'
]
*/

Comments

Your Answer

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