How to overwrite an objects values using an array php

Viewed 700

I have the following array containing one or more objects:

array:1 [▼
  0 => ApiS7File {#484 ▼
    +id: 19
    +type: "file"
    +z: "e1a4f81f.f90428"
    +name: ""
    +filename: "example/example.txt"
  }
]

If the user suplies me with an options array

$options = ['filename' => 'hello', 'name' => 'thanks']

I want the array object to be overwritten using the user suplied values:

array:1 [▼
  0 => ApiS7File {#484 ▼
    +id: 19
    +type: "file"
    +z: "e1a4f81f.f90428"
    +name: "thanks"
    +filename: "hello"
  }
]

How can I achieve this?

2 Answers

This might solve your problem.

//assuming $arr is your array

foreach($arr as $a){
   foreach($options as $key=>$value){
       $a->$key = $value;
   }
}
return $arr;

You can use array_replace,

$result = array_replace($yourArray, $options);

Here is syntax for the same

$basket = array_replace($base, $replacements,// you can pass multiple arrays);
Related