-3

可以在 PHP 两个 JSON 上加入、查找和打印未加入的行吗?数据看起来像这样:

[{"column_name":"test","position":10},{"column_name":"test2","position":12},{"column_name":"test3","position":14}]

[{"dbcolumnname":"test"},{"dbcolumnname":"test3"}]

输出应如下所示:

[{"column_name":"test2","position":12}]

提前感谢您的帮助。

4

1 回答 1

0

这个 ?

<?
$json = '[{"column_name":"test","position":10},{"column_name":"test2","position":12},{"column_name":"test3","position":14}]';
$db_json = '[{"dbcolumnname":"test"},{"dbcolumnname":"test3"}]';

// Convert json to arrays of objects
$array = json_decode($json);
$db_array = json_decode($db_json);

// Extract all dbcolumnnames
$dbcolumnnames = array();
foreach($db_array as $v){
    $dbcolumnnames[] = $v->dbcolumnname;
}

// Rebuild an array with $array's objects where column_name is not in dbcolumnnames
$new_array = array();
foreach($array as $v){
    if (!in_array($v->column_name , $dbcolumnnames)) {
        $new_array[]=$v;
    }
}

// echo it, json encoded :
echo( json_encode($new_array) );
// will display :
// [{"column_name":"test2","position":12}]
?>
于 2013-04-26T13:03:38.523 回答