我不知道该怎么做才能做到这一点。我尝试了多种方法,例如我使用array_map
,array_walk
,嵌套foreach
循环get_object_vars
,我使用json_decode/encode
等等。我总是来得更远,但从未实现我的目标,我想得到你的一些指导
基本上当你看到下面的数组时,如果你想在path
数组中为数组本身的多个值更改某些值,你将如何继续?
我的问题:
1)我是否必须首先将两个嵌套对象转换为数组,或者这不是必须这样做的吗?我的意思是我总是得到一些类型转换错误,它告诉我,我要么将所有内容都作为对象或数组。这是对的吗?
2)如果这个问题得到解决,哪个php数组函数适合更改数组(/ object)中的值?正如我上面所写,我尝试了很多,我再也看不到树林里的树木了。你建议我在foreach循环中使用哪一个?
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
答案 0 :(得分:1)
我会建议,
例如
// array defined as point 1
$change_path_array= array('pics'=>'pictures','meal'=>'food');
// $array is your array.
foreach ($array as $value) {
// loop you path array
for($i=0;$i<count($value->doc->path);$i++){
// check if the value is in defined array
if(in_array($value->doc->path[$i],$change_path_array)){
// get the key and replace it.
$value->doc->path[$i] = array_search($value->doc->path[$i], $change_path_array);
}
}
}
Out Put:用照片替换图片和食物
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pics
[2] => meal
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pics
[2] => vacations
[3] => rome
)
)
)
)
您可以修改代码以检查区分大小写。
答案 1 :(得分:0)
你可以这样做:
for($i = 0; $i < count($arr); $i++){
$path_array = $arr[$i]->doc->path;
// do your modifications for [i]th path element
// in your case replace all 'Bob's with 'Joe's
$path_array = array_map(function($paths){
if($paths == 'Bob') return 'Joe';
return $paths;
}, $paths_array);
$arr[$i]->doc->path = $path_array;
}
答案 2 :(得分:0)
将所有pictures
更改为photos
的示例:
$doc1 = new \stdClass;
$doc1->doc = new \stdClass;
$doc1->doc->path = array('Bob', 'pictures', 'food');
$doc2 = new \stdClass;
$doc2->doc = new \stdClass;
$doc2->doc->path = array('Alice', 'pictures', 'vacations', 'rome');
$documents = array($doc1, $doc2);
/* change all 'pictures' to 'photos' */
foreach ($documents as &$doc) {
foreach ($doc->doc->path as &$element) {
if ($element == 'pictures') {
$element = 'photos';
}
unset($element);
}
unset($doc);
}
print_r($documents);