I received this from an Ajax call in my PHP page:
[{"id":8},{"id":10},{"id":11},{"id":12}]
How can I parse it in order to have something like this :
array(8, 10, 11, 12)
Thanks.
You can use array_map for that:
<?php
$array = json_decode( '[{"id":8},{"id":10},{"id":11},{"id":12}]' );
function getId($n) {
return($n->id);
}
$mapped = array_map("getId", $array);
var_dump($mapped);
?>
http://sandbox.onlinephpfunctions.com/code/e74f6252bcf9b321115af8626ca7ebc192414730
First of all you need to decode your json to an array, then iterate it and grab your values. Something like this.
<?php
$json = '[{"id":8},{"id":10},{"id":11},{"id":12}]';
$array = json_decode($json, true);
$result = array_map(static function ($el) {
return $el['id'];
}, $array);
print_r($result);
First, let's look what you have here.
[{"id":8},{"id":10},{"id":11},{"id":12}]
is the json representation of an array that contains objects. We can use the function json_decode
to get the data out of such a json representation.
var_dump(json_decode($json));
would look like this:
array(4) {
[0]=>
object(stdClass)#1 (1) {
["id"]=>
int(8)
}
[1]=>
object(stdClass)#2 (1) {
["id"]=>
int(10)
}
[2]=>
object(stdClass)#3 (1) {
["id"]=>
int(11)
}
[3]=>
object(stdClass)#4 (1) {
["id"]=>
int(12)
}
}
But now let's have a look a the docs. json_decode
has more than one parameter. The second parameter states if objects should be converted to associative arrays.
So var_dump(json_decode($json, true));
would give us something like this:
array(4) {
[0]=>
array(1) {
["id"]=>
int(8)
}
[1]=>
array(1) {
["id"]=>
int(10)
}
[2]=>
array(1) {
["id"]=>
int(11)
}
[3]=>
array(1) {
["id"]=>
int(12)
}
}
But now we want to have the value of every of these arrays. While we could do this with a simple loop, PHP has a lot of inbuilt array functions. So let's look, what could be working for us.
Let's take array_map
. This function takes a callable (could be function) and an array and returns an array. (For details visit the docs.)
$result = array_map(function ($value) {
return $value['id'];
}, json_decode($json, true));
var_dump($result);
This would give us
array(4) {
[0]=>
int(8)
[1]=>
int(10)
[2]=>
int(11)
[3]=>
int(12)
}
Explanation: We replace every array in the array with the id value in the array.