Reputation: 61
So I have this json file
[
{
"var1": "6",
"var2": "13",
"var3": "17"
},
{
"var1": "9",
"var2": "11",
"var3": "6"
}
]
How can I get only the values of var2
which are 13
and 11
?
Upvotes: 1
Views: 3332
Reputation: 3467
You can use json_decode
alongside array_column
, no need for unnecessary loops.
array_column(json_decode($json_string, true), 'var2'); // [13, 11]
For array_column
the first argument is the array, second argument being the key you want to access.
json_decode
the first argument is a string - your json. The second argument tells it to return an array and not stdClass
.
http://php.net/manual/en/function.array-column.php
Upvotes: 3
Reputation:
You can use json_decode
function, then use foreach
to get the values you want
$data = json_decode("your.json");
foreach ($data as $obj) {
print $obj->var2;
}
json_decode
let you to choose the data format to be retrieved (object or associative array), if you prefer associative array style, just pass true as second parameter to json_decode
$data = json_decode("your.json", true);
foreach ($data as $obj) {
print $obj['var2'];
}
Upvotes: 1
Reputation: 33
use json_decode()
$json = '[{ "var1": "6", "var2": "13", "var3": "17"},{ "var1": "9", "var2": "11", "var3": "6"}];'
$array = json_decode ($json, true);
$values = [];
foreach ($array as $ar) {
$values[] = $ar['var2'];
}
var_dump($values);
Upvotes: 1