PHP-JSON到Array,迭代并打印到字符串

时间:2018-10-09 07:48:58

标签: php arrays json laravel

我在HTTP请求中收到以下JSON对象:

    std::thread th2;

std::thread th1([&] () {


    th2 = std::thread([&] () {

        //do something;
    });

});


cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(core, &cpu_set); // lets say 2
pthread_setaffinity_np(th1.native_handle(), sizeof(cpu_set_t), &cpu_set);


th2.join();
th1.join();

我想获取诸如{ "name": "myjsonstring", "statisticalvalues": [ { "key_0":"677876" }, { "key_0":"0" }, ], "commoditycodes": [ { "key_0":"90001000" }, { "key_0":"80001000" }, ] } 之类的上述值,例如:

statisticalvalues & commoditycodes

我最初的想法是将其添加到数组中

JSON Information:
677876      90001000
0           80001000

然后我想像上面一样输出它,但是我不确定如何像这样 $returnArray = []; //Input foreach ($request->input() as $key => $value) { if ($key === 'commoditycodes') { $returnArray['commoditycodes'][] = $value; } if ($key === 'statisticalvalues') { $returnArray['statisticalvalues'][] = $value; } }

进行迭代。
statisticalvalues |  commoditycodes

我走对了吗?谁能帮助我生成正确的输出格式?

1 个答案:

答案 0 :(得分:4)

首先使用json_decode()解码JSON。然后遍历其statisticalvalues,在commoditycodes数组中找到具有相同数组索引的相应commoditycodes。请记住,实际值在名为key_0的属性下。

<?php
$json = '{"name":"myjsonstring","statisticalvalues":[{"key_0":"677876"},{"key_0":"0"}],"commoditycodes":[{"key_0":"90001000"},{"key_0":"80001000"}]}';
$obj = json_decode($json,false);
foreach ($obj->statisticalvalues as $key => $value) {
    echo $value->key_0 . "\t\t" . $obj->commoditycodes[$key]->key_0 . "\n";
}
?>

在您的情况下,可能是:

<?php
$obj = $request->input();
foreach ($obj["statisticalvalues"] as $key => $value) {
    echo $value["key_0"] . "\t\t" . $obj["commoditycodes"][$key]["key_0"] . "\n";
}
?>