php - How can I remove the key of array object and keep them as array?

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"
}
],
Answer
Solution:
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"
],
Answer
Solution:
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 ajson_decode
call. You canmap
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'
]
*/
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object not found by the @paramconverter annotation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.