Skip to content
Advertisement

Change value for object on foreach php

I have one array same this:

    $object = new stdClass();
    $object->name = "test";
    $object->age = "24";
    $object1 = new stdClass();
    $object1->name = "test1";
    $object1->age = "25";
    $array = array("23" => $object, "24" => $object1);

    $array2 = [ 
        "23" => ["name" => "John Nathan"],
        "24" => ["name" => "test 25"]
    ];
    foreach ($array as $key => $item){
        if(isset($array2[$key])){
            $item->name = $array2[$key]['name'];
        }
    }
    var_dump($array);

I don’t understand why the array displays like this:

    array(
        'name' => 'test 25',
        'age'  => '24'
        )
    array(
        'name' => 'test 25',
        'age'  => '25'
    )
    

I expect it to show up like this:

   array(
        'name' => 'John Nathan',
        'age'  => '24'
        )
    array(
        'name' => 'test 25',
        'age'  => '25'
    )

Please advise me on how to make it work as expected. Thanks

Advertisement

Answer

 <?php $object = new stdClass();
$object->name = "test";
$object->age = "24";
$object1 = new stdClass();
$object1->name = "test1";
$object1->age = "25";
$array = array("23" => $object, "24" => $object1);

$array2 = [
    "23" => ["name" => "John Nathan"],
    "24" => ["name" => "test 25"]
];

foreach ($array as $key => $item) {
    foreach ($array2 as $key2 => $item2) {
        if ($key == $key2) {
            $item->name = $item2["name"];
        }
    }
}

print_r($array);
?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement