如何使用php数组覆盖对象值
我的以下数组包含一个或多个对象:如何使用php数组覆盖对象值,php,arrays,laravel,Php,Arrays,Laravel,我的以下数组包含一个或多个对象: array:1 [▼ 0 => ApiS7File {#484 ▼ +id: 19 +type: "file" +z: "e1a4f81f.f90428" +name: "" +filename: "example/example.txt" } ] 如果用户向我提供选项数组 $options = ['filename' => 'hello', 'name' => 'thanks'] 我希望使用
array:1 [▼
0 => ApiS7File {#484 ▼
+id: 19
+type: "file"
+z: "e1a4f81f.f90428"
+name: ""
+filename: "example/example.txt"
}
]
如果用户向我提供选项数组
$options = ['filename' => 'hello', 'name' => 'thanks']
我希望使用用户提供的值覆盖数组对象:
array:1 [▼
0 => ApiS7File {#484 ▼
+id: 19
+type: "file"
+z: "e1a4f81f.f90428"
+name: "thanks"
+filename: "hello"
}
]
如何实现这一点?您可以使用array\u replace
$result = array_replace($yourArray, $options);
下面是相同的语法
$basket = array_replace($base, $replacements,// you can pass multiple arrays);
这可能会解决你的问题
//assuming $arr is your array
foreach($arr as $a){
foreach($options as $key=>$value){
$a->$key = $value;
}
}
return $arr;
感谢您的回答,但是数组_replace不起作用,因为数组包含对象,因此不是数组:-)是ArrayObject的ApiS7File实例吗?用户提供的数组是否只包含有效密钥?或者您需要验证提供的数据吗?