PHP traverses two array problems for advice and uses the value of B to fill the value of A.

Array A:

$a = [
    0 => ["num" => 100],
    1 => ["num" => 105],
    3 => ["num" => 253],
    N.......
]

Array B:

$b = [
    0 => [
        "id" => 1,
        "num" => 300
    ],
    1 => [
        "id" => 2,
        "num" => 600
    ],
    2 => [
        "id" => 3,
        "num" => 900
    ],
    N........
]

question: I want to traverse the records with num less than 500in array A, and then use the num in array B to fill it. If the num in array An is equal to 500, skip it. Finally, there is an array to record the ID in array B. those ID participated in the filling, and ask for instructions on how to withdraw cash under the code. Looks like it"s going to be recursive?

Mar.10,2021

pseudo code is as follows

// b 
$index = 0
// b  
$contains = []
// for  a
for ():
    if (a [i]>= 500) 
        continue
    else 
        a[i].num  = b[$index].num
        $contains.push(b[$index].id)
        $indexPP

Sorry, php learned but forgot that if b can fill an at will, it's OK
if b has to be greater than 500 to fill, you can just get rid of b less than 500

.

Let me also say a thought:

  1. use array_filter to screen out the conditions in the array a
  2. for the first time array_replace , replace the sifted value
  3. in [1] with the array b.
  4. for the second time array_replace , replace the value in array a with [2]
  5. run through the loop, using array_key_exists to determine whether there is a key, named 'id'' for each array element in array a. If so, put the whole push into a new array and unset drop
  6. .

may not be very elegant. It's just one more angle.


the following is key in $a is id

in $b
 $a = collect($a)->map(function($a1, $key) use($b){
        if($a1['num'] < 500){
            $b1 = collect($b)->reject(function($b1) use($key){
               return $b1['id'] != $key;
            });
            $b1 = $b1->flatMap(function($xx){
                return $xx;
            });

            if (!empty($b1->toArray())){
                $a1['num'] = $b1['num'];
                $a1['index'] = $b1['id'];
                return $a1;
            }  
        }
    })->filter(function($v){
        return !empty($v);
    });

    dd($a);
Menu