使用来自 JSON 的键、值和对象平展多维数组


Flatten a Multidimensional Array with key, value and object from a JSON

2天,我试图从多维数组中提取信息,我想我在尝试了很多事情后陷入

困境

这是我的 json

{
  "profile": [
    {
      "id": "123456",
      "hostId": null,
      "description": [
        {
          "id": "name",
          "value": "foo"
        },
        {
          "id": "name2",
          "value": "foo2"
        },
        {
          "id": "bio",
          "value": "heyyyy"
        },
        {
          "id": "location",
          "value": "somewhere"
        }
      ],
      "ishere": true
    }
  ]
}

我想操纵它来拥有这个

{
  "id": "123456",
  "host": null,
  "name": "foo",
  "name2": "foo2",
  "bio": "heyyyy",
  "location": "somewhere",
  "ishere": true
}

有了这个(json_decode后)

        foreach ($array->profileUsers[0]->settings as $item) {
            $out2[$item->id] = $item->value;
        }

我只有

{  
  "name": "foo",
  "name2": "foo2",
  "bio": "heyyyy",
  "location": "somewhere"
}

谢谢

这应该可以解决问题:

$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
    $obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
  if(is_array($item)) {
     $new_array[$item['id']] = $item['value'];
  }
  else {
     $new_array[$key] = $item;
  }
}

硬编码这个,希望它会有所帮助。