How to use primitive functions to extract subarrays that meet the conditions in a two-dimensional array
ababaaid
ab:
$array=[
["id"=>1,"name"=>"name1","value"=>"value1"],
["id"=>1,"name"=>"name2","value"=>"value2"],
["id"=>2,"name"=>"name3","value"=>"value3"],
["id"=>3,"name"=>"name4","value"=>"value4"],
["id"=>3,"name"=>"name5","value"=>"value5"],
.......
];
idaid==1:
$end=[
["id"=>1,"name"=>"name1","value"=>"value1"],
["id"=>1,"name"=>"name2","value"=>"value2"],
];
the function prototypes of most groups of native functions are also looped to the array. Unless your array is extremely large and complex, foreach will not have any efficiency problems
the description of the subject is rather messy. I don't know if I understand it this way or not.
there are two arrays an and b. The array structure is as follows:
$a = [['id' => '1', 'name' => 'name1'],['id' => '2', 'name' => 'name2']];
$b = [['id' => '1', 'value' => 'value1'],['id' => '2', 'value' => 'value2']];
then the goal is to add some of the data from array b to array a to get a data similar to this:
$c = [['id' => '1','name' => 'name1' ,'value' => 'value1'],['id' => '2','name' => 'name2', 'value' => 'value2']];
in this case, if both arrays are large, for example, there are about 10000 sets of data, the direct double loop does have performance problems.
this problem can improve performance by setting one of the arrays to key-value based on id. The code is as follows:
$storage_a = [];
foreach($a as $value) {
$storage_a[$value['id']] = $value;
}
foreach($b as $value) {
if(isset($storage_a[$value['id']])) {
$storage_a[$value['id']]['value'] = $value['value'];
}
}
print_r($storage_a);
whether the native functions of specific PHP achieve similar functions, the subject can check the PHP manual.
because the subject is one-to-many content, the code needs to be adjusted according to the actual situation.
from a performance point of view, the complexity of a direct double loop is O (nimm), so the complexity of writing can be roughly regarded as O (nimm).
if you don't want to loop nesting, use array_reduce ()