如何用php将json值存储到数组中?

时间:2018-02-17 12:13:54

标签: php arrays json

我需要在数组中输入“total_value”的所有值以及来自json url的“car_id”的所有值。

JSON:

[
  {
    "control": {
      "color": "blue",
      "total_value": 21.5,
      "car_id": 421118
    }
  },
  {
    "control": {
      "color": "green",
      "total_value": 25,
      "car_id": 421119
    },
  {
    "control": {
      "color": "red",
      "total_value": 18,
      "car_id": 421519
    }
}
]

我的Php:

<?php

$getJson = file_get_contents("http://url.com/control.json",false);

$j = json_decode($getJson);

3 个答案:

答案 0 :(得分:2)

您的json格式不正确,缺少}

您可以循环播放$j并获取$item->control->total_value之类的值。 然后将您要查找的2个值添加到数组中,并将该数组添加到$result

$j = json_decode($data);
$result = [];
foreach ($j as $item) {
    array_push($result,[
        'total_value' => $item->control->total_value,
        'car_id' => $item->control->car_id
    ]);
}

Php output example

答案 1 :(得分:0)

这样的事情:

$result = [];
foreach ($j as $item) {
    array_push($result, [
        'total_value' => $item['total_value'],
        'car_id' => $item['car_id']
    ]);
}

答案 2 :(得分:0)

您也可以使用array_walk()并删除您不想要的项目来实现此目的,这是一个较短的代码量,并且不需要您创建临时变量或从对象开始并最终用数组。

array_walk($obj, function(&$v, $k) {
    unset($v->control->color);
});

所以例如(修复破碎的json)

<?php
$json = '[{
        "control": {
            "color": "blue",
            "total_value": 21.5,
            "car_id": 421118
        }
    },
    {
        "control": {
            "color": "green",
            "total_value": 25,
            "car_id": 421119
        }
    },
    {
        "control": {
            "color": "red",
            "total_value": 18,
            "car_id": 421519
        }
    }
]';

$obj = json_decode($json);

array_walk($obj, function(&$v, $k) {
    unset($v->control->color);
});

print_r($obj);

https://3v4l.org/hXada

<强>结果:

Array
(
    [0] => stdClass Object
        (
            [control] => stdClass Object
                (
                    [total_value] => 21.5
                    [car_id] => 421118
                )

        )

    [1] => stdClass Object
        (
            [control] => stdClass Object
                (
                    [total_value] => 25
                    [car_id] => 421119
                )

        )

    [2] => stdClass Object
        (
            [control] => stdClass Object
                (
                    [total_value] => 18
                    [car_id] => 421519
                )

        )

)