使用特定查询从JSON创建PHP数组

时间:2018-07-28 14:16:42

标签: php arrays json

我有一个要检索的JSON文件

// Sample JSON Results
 [
     {
         "serial": "A",
         "timeStamp": "2018-07-28 04:00:00",
         "value1": "0.000000",
         "value2": "0.000192",
         "value3": "1.000000"
     },
     {
         "serial": "B",
         "timeStamp": "2018-07-28 04:00:00",
         "value1": "0.000000",
         "value2": "0.000191",
         "value3": "1.000000"
     },
     {
         "serial": "C",
         "timeStamp": "2018-07-28 04:00:00",
         "value1": "0.000000",
         "value2": "0.000191",
         "value3": "1.000000"
     },    
     {
         "serial": "A",
         "timeStamp": "2018-07-28 05:00:00",
         "value1": "0.000000",
         "value2": "0.000191",
         "value3": "1.000000"
     },
     {
         "serial": "B",
         "timeStamp": "2018-07-28 05:00:00",
         "value1": "0.000000",
         "value2": "0.000191",
         "value3": "1.000000"
     },
     {
         "serial": "C",
         "timeStamp": "2018-07-28 05:00:00",
         "value1": "0.000000",
         "value2": "0.000191",
         "value3": "1.000000"
 }
 ]

我的问题是我如何遍历此数组以仅检索序列作为示例,显示具有所有3个值的序列A结果

// Sample JSON Results[
    {
        "timeStamp": "2018-07-28 04:00:00",
        "value1": "0.000000",
        "value2": "0.000192",
        "value3": "1.000000"
    },
    {
        "timeStamp": "2018-07-28 05:00:00",
        "value1": "0.000000",
        "value2": "0.000191",
        "value3": "1.000000"
    }
]

输出格式为php数组,我只是不确定如何以A来查询序列,然后以value1value2的值检索所有唯一时间戳,value3

[
[timestamp,
value1,
value2,
value3],
[timestamp
value1,
value2,
value3],
[timestamp,
value1,
value2,
value3]
]

2 个答案:

答案 0 :(得分:0)

您可以使用array_filter函数

下面是示例。它将返回从列表中选择的数据集,您必须传递参数,$ list是对象和数组,$ key是您在列表中找到的键,$ value是您必须找到的键的值

function filterList($list, $key, $value) {
   return array_filter($list, function($a) {
         return $a[$value] == $value;
    });

 }

希望它对您有帮助!

答案 1 :(得分:0)

该过程实际上涉及多个步骤。

步骤1:将JSON数据转换为PHP数组。

第2步:过滤数组,仅保留序列号= A的那些数组。

第3步:删除第2步中找到的每个阵列的串行索引。

第4步:将数据转换回JSON。

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once './vendor/autoload.php';

use FormGuide\Handlx\FormHandler;


$pp = new FormHandler();

$validator = $pp->getValidator();
$validator->fields(['name','email'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('message')->maxLength(6000);


$pp->requireReCaptcha();
$pp->getReCaptcha()-
>initSecretKey('');


$pp->sendEmailTo('marcogianni.webdev@gmail.com'); // ← Your email here
//  $pp->sendEmailTo(['someone@gmail.com',
'another@gmail.com','more@gmail.com']); (for more than one email addresses

echo $pp->process($_POST);`