Home > OS >  update array values ​from other array data without changing the array structure
update array values ​from other array data without changing the array structure

Time:09-05

I have this example php array

array [
    [0] => array [
                   month1=> 'qwe',
                   month2 => 'rty' 
                   month3 => '' 
                 ],
    [1] => array [
                   month1=> 'asd',
                   month2 => 'fgh' 
                   month3 => '' 
                 ],
    [2] => array [
                   month1=> 'zxc',
                   month2 => 'vbn' 
                   month3 => '' 
                 ]
]

I want to change the old month3 data with the new month3 data, without changing the old array structure

array [
    [0] => array [
                  month1=> 'qwe',
                   month2 => 'rty' 
                   month3 => 'uio' 
                 ],
    [1] => array [
                   month1=> 'asd',
                   month2 => 'fgh' 
                   month3 => 'jkl' 
                 ]
     [2] => array [
                   month1=> 'zxc',
                   month2 => 'vbn' 
                   month3 => 'nm' 
                 ]
    ]

this my php code:

    foreach ($tempsell1 as $id =>$pen){ 
        $sell[$id] =   
        [
            'month1' => $pen->month1,
            'month2' => $pen->month2,
            'month3' => '',
        ];
    }
    foreach ($tempsell2 as $id => $pen){ 
        $sell[$id]= [
            'month3' => $pen->month3,
        ];
    }
    dd($sell);

the expected result is not the same what I want, please help, thank you

CodePudding user response:

No need of two foreach()

foreach ($tempsell1 as $id =>$pen){ 
        $sell[$id] =   
        [
            'month1' => $pen->month1,
            'month2' => $pen->month2,
            'month3' => isset($tempsell2[$id]->month3) ? $tempsell2[$id]->month3 : $tempsell1[$id]->month3, // use key of first array to get data from second array
        ];
    }
   
    dd($sell);

CodePudding user response:

In my opinion, you want to change the value of the key 'month3' in a two-dimensional array.

In your case, you can do it like this $sell[$id]['month3']= $value;

Below is the updated version of your code.

  foreach ($tempsell1 as $id =>$pen){ 
        $sell[$id] =   
        [
            'month1' => $pen->month1,
            'month2' => $pen->month2,
            'month3' => '',
        ];
    }
    foreach ($tempsell2 as $id => $pen){ 
        // 'month3' is the key
        $sell[$id]['month3']= $pen->month3;
    }
    dd($sell);
  •  Tags:  
  • php
  • Related