拥有以下2个数组:
[
{"id":1,"value":40},
{"id":2,"value":30}
]
和
[
{"userId":1,"worth":20},
{"userId":2,"worth":10}
]
我最终想要的是以下结果:
[
{"id":1,"value":20},
{"id":2,"value":10}
]
所以在这里,我想根据“d”在第一个数组中替换第二个数组中的值。我做了类似的事情:
foreach ($array2 as $k => $v) {
array_filter($array1), function($item) use($value) {
$item['id'] == $v['userId'] ? $item['value'] = $v['worth'] :$item['value'] = $item['value'];
});
}
它适用于那些给定数组,但是如果你有超过100万个数据的数组,它将永远不会完成! 问题是,如果有一些PHP功能可以做这项艰苦的工作吗?
数组格式已更新,现在我应该使用以下格式:
[
0 => stdClass {"id":1,"value":40},
1 => stdClass {"id":2,"value":30}
]
和
[
0 => Statement {"userId":1,"worth":20},
1 => Statement {"userId":2,"worth":10}
]
数组1:
array (size=2)
0 =>
object(stdClass)[2721]
public 'value' => float 84
public 'id' => int 1229
1 =>
object(stdClass)[2707]
public 'value' => float 144
public 'id' => int 1712
数组2:
array (size=2)
0 =>
object(Bank\Accounting\Statement)[2754]
public 'worth' => float 572
public 'userId' => int 1229
1 =>
object(Bank\Accounting\Statement)[2753]
protected 'worth' => float 654
protected 'userId' => int 1712
答案 0 :(得分:1)
您可以使用array_column
将userId
作为关键字,worth
作为值。
使用map
重复第一个数组。检查密钥是否存在,如果存在则替换value
。
$arr1 = [{"id":1,"value":40},{"id":2,"value":30}];
$arr2 = [{"userId":1,"worth":20},{"userId":2,"worth":10}];
//Use array_column to make the userId as the key and worth as the value.
$arr2 = array_column($arr2, 'worth', 'userId');
//Use `map` to reiterate the first array. Check if the key exist on $arr2, if exist replace the `value`. If not replace it with empty string.
$results = array_map( function($v) use ( $arr2 ) {
$valueInArr2 = array_search($v->id, array_column($arr2, 'userId'));
$v->value = $valueInArr2 ? $valueInArr2 : "";
return $v;
}, $arr1);
echo "<pre>";
print_r( $results);
echo "</pre>";
这将导致:
Array
(
[0] => Array
(
[id] => 1
[value] => 20
)
[1] => Array
(
[id] => 2
[value] => 10
)
)
更新:使用对象。我没有测试过这个。
$arr1 = .....;
$arr2 = .....;
//Make the object into array
$arr2 = array_reduce($arr2, function($c,$v) {
$c[ $v->userId ] = array(
'worth' => $v->worth;
'userId' => $v->userId;
);
return $c;
},array());
//Update the first array
$results = array_map( function( $v ) use ( $arr2 ) {
$val = array( 'id' => $v->id );
$val['value'] = isset( $arr2[ $v->id ] ) ? $arr2[ $v->id ] : "";
return $v;
}, $arr1);
答案 1 :(得分:1)
你可以尝试这种方式(使用laravel集合):
$arr1 = '[{"id":1,"value":40},{"id":2,"value":30}]';
$arr2 = '[{"userId":1,"worth":20},{"userId":2,"worth":10}]';
$arr1 = json_decode($arr1, true);
$arr2 = json_decode($arr2, true);
$col2 = collect($arr2);
foreach ($arr1 as &$value) {
$value['value'] = $col2->where('userId', $value['id'])->first()['worth'];
}
echo "<pre>";
print_r($arr1);
输出:
Array
(
[0] => Array
(
[id] => 1
[value] => 20
)
[1] => Array
(
[id] => 2
[value] => 10
)
)