PHP:根据一个键上的组从 Json 数组创建多个 Json 数组

标签 php mysql arrays json

我有一个如下所示的 JSON 数组:-

[{
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06",

}, {
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06",

}, {
    "order_no": "G1049",
    "contract_no": "DCI-37500029",
    "dc_in_date": "2017-11-06",

}]

我想创建数组数量,其中包含类似contract_no的所有键值对。对于上面的示例,我想要输出如下:-

数组-I

[{
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06",

}, {
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06",

}]

数组-II

[ {
    "order_no": "G1049",
    "contract_no": "DCI-37500029",
    "dc_in_date": "2017-11-06",

}]

基本想法是我有一个有两列的 Mysql 表。一种是“contract_no”,另一种是“order_details”。我想将 order_details 的值更新为契约(Contract)号匹配的 Array-I 和 Array-II。

有办法做到这一点吗?

最佳答案

您可以使用 array_search 和 array_column 方法。

<?php

function recursive_array_search($needle,$haystack) {
    $return = null;
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value || (is_array($value) && recursive_array_search($needle,$value) !== null)) {
            $return[] = $current_key;
        }
    }
    return $return;
}

$json = '[{
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06"
}, {
    "order_no": "1",
    "contract_no": "DCI-92700028",
    "dc_in_date": "2017-11-06"
}, {
    "order_no": "G1049",
    "contract_no": "DCI-37500029",
    "dc_in_date": "2017-11-06"
}]';
$array = json_decode($json, true);
echo '<pre>';
    print_r($array);
    echo '</pre>';
$columns = array_column($array,'contract_no');
foreach($columns as $column){
    echo 'Contact No:'.$column.'<br />';
    $found_key = recursive_array_search($column, $array);
    echo '<pre>';
    print_r($found_key);
    echo '</pre>';

}
?>

关于PHP:根据一个键上的组从 Json 数组创建多个 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153003/

相关文章:

mysql - 如何将 HH、MM、AM/PM 日期存储到 MySQL

javascript - 如何将菊花链/点表示法中的 JavaScript 对象展开为具有嵌套对象和数组的对象?

C 程序抛出运行时错误

php - 如何使用 cakephp 3.0 在 redis 中保存 session ?

php - 类似 jQuery Facebook 的评论系统

php - LARAVEL - 未找到基表或 View : 1146 Table doesn't exist (SQL: select * from )

javascript - 使用 PHP 将查询结果存储在数组中,并在 Javascript 中使用该数组

php - httppost mysql 为空

php - Mysql 查询查找给定日期范围内某个值出现的次数

mysql - 如何为以下内容创建 mysql 查询?