使用JSON中的键,值和对象展平多维数组

时间:2022-11-26 20:14:00

For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things

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

Here is my json

这是我的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
    }
  ]
}

I want to manipulate it to have this

我想操纵它来拥有它

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

with this (after a json_decode)

用这个(在json_decode之后)

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

I only have

我只有

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

Thank you

2 个解决方案

#1


1  

This should do the trick:

这应该是诀窍:

$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
    $obj->{$d->id} = $d->value;
unset($obj->description);

#2


0  

$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;
  }
}

Hardcoded this, hope it will help.

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

#1


1  

This should do the trick:

这应该是诀窍:

$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
    $obj->{$d->id} = $d->value;
unset($obj->description);

#2


0  

$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;
  }
}

Hardcoded this, hope it will help.

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