Answer
Solution:
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 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.
Sovar_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 . 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.