1

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@FaizalAnwar I am glad to help you.
1

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);

1 Comment

This step is also correct, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.