2

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
  • Is ApiS7File instanceof ArrayObject? Commented Jun 20, 2019 at 8:22
  • will the user-supplied array only contain valid keys? or do you need to validate the supplied data? Commented Jun 20, 2019 at 18:22

2 Answers 2

2

This might solve your problem.

//assuming $arr is your array

foreach($arr as $a){
   foreach($options as $key=>$value){
       $a->$key = $value;
   }
}
return $arr;
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you for your answer, but the array_replace does not work because the array contains an object and is therefore not an array :-)

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.