Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update array values ​from other array data without changing the array structure

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading