I am trying to get all ids from json by using json_decode function for this response.How can I get only id in an array? I really appreciate any help.
Response:
{
"columns": [
"name",
"id",
"sno"
],
"data": [
[
"test1",
"123",
"1"
],
[
"test2",
"456",
"2"
]
]
}
Code:
$obj = json_decode($result, true);
foreach ($obj as $key => $value) {
foreach ($value as $k => $val) {
echo $val;
if ($k == "id") {
array_push($all_ids, $val);
}
}
}
$obj = json_decode($result);
$all_ids = array();
foreach ($obj->data as $el) {
array_push($all_ids, $el[1]);
}
$ids = array_map(function($a){return $a[1];}, $obj['data']);
You could do it as follows, using in_array and array_map:
$obj = json_decode($result);
// identify which column number corresponds to "id"
$idColumnNo = in_array('id', $obj->columns);
// collect the elements at that column number from the data array
$all_ids = array_map(function ($elem) {
return $elem[$idColumnNo];
}, $obj->data);