I’m trying to figure out how to implode a json array coming from an axios call, within a php file. I currently have this function where I toggle between dumping out the array and then trying to dump the imploded version but that fails stating that it’s an invalid argument for a foreach.
PHP file:
public function getResults(array $num = []){
dd($num);
dd(implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $p;} }, $num)));
}
The dd($num) call shows this in my network console:
array:2 [
0 => "{"number":"115"}"
1 => "{"number":"135"}"
]
How can I implode this to look like 115,135
?
2
Answers
You should use php’s built in function json_decode($data) to decode json.
You Will not get it in the format you have show, but as a stdClass by default.
If you oass a 2nd argument to json_decode (true or false) you will get it as and associative array og you are more comdortable with that.
I would have provided a better usage example, but the editor is not coorporating on my mobile device.
Test https://3v4l.org/HUmuM
Issues with your code
PHP receives JSON as a string. So you need to decode that string so it makes sense for your code as a data structure.
You have an array of objects.
array_map
already iterates through the array and exposes the stringified objects inside its scope. So I see no need for the extra loop.Even if you did decode the object as an associative array you could just do
return $obj['number']
.($obj as $p => $v) { return $p;}
would always return"number"
which is the key.Fix for the comment feedback
https://www.php.net/manual/en/functions.arrow.php