我试图通过使用json_decode函数来获取来自json的所有ID。如何才能获得数组中的id?我真的很感激任何帮助。
响应:
{
"columns": [
"name",
"id",
"sno"
],
"data": [
[
"test1",
"123",
"1"
],
[
"test2",
"456",
"2"
]
]
}
代码:
$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);
}
}
}
答案 0 :(得分:2)
$obj = json_decode($result);
$all_ids = array();
foreach ($obj->data as $el) {
array_push($all_ids, $el[1]);
}
答案 1 :(得分:2)
您可以使用in_array和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);
答案 2 :(得分:1)
$ids = array_map(function($a){return $a[1];}, $obj['data']);