为多维数组的特定索引定义值



我正在尝试创建一个函数,将新值分配给多维数组中的特定索引:

  1. 我有一个像这样的数组:

    数据[我]("签入");

    数据[我]("结帐");

    数据[我]("内容")[x][价格];

    数据[我]("内容")[x]("利润");

    数据[我]("内容")[x] [' exchangerate '];

我的函数的第一个参数将获得数组,第二个参数将获得我想要重新定义的索引:

例如:

function defineNewValues(&$arr, $keys) {
//logic
}

调用函数:

defineNewValues($myArray, [
'data.*.content.*.price' => 0,
'data.*.content.*.profit => 0,
]);

我相信递归是我的问题的关键,但不知道怎么解决。

谢谢。

这样可以吗?

我只要求你学习这段代码,而不是实现它,原因很简单,将来你可能会遇到同样类型的问题。


function setValue($key,$value,&$array){
$find_parts = explode(".", $key);
$find = $find_parts[0]??null;
if ($find!=null){
if ($find == "*"){
array_shift($find_parts);
foreach($array as &$sub_array){
setValue(implode(".",$find_parts),$value,$sub_array);
}
}else{
if (count($find_parts)>1){
if (array_key_exists($find,$array)){
array_shift($find_parts);
setValue(implode(".",$find_parts),$value,$array[$find]);
}
}else{
if (array_key_exists($find,$array)){
$array[$find] = $value;
}
}
}
}
}
function defineNewValues(&$arr, $keys) {
foreach($keys as $key=>$value){
setValue($key,$value,$arr);
}
}

$myArray=[
"data"=>[
"a"=>[
"content"=>[
"aa"=>[
"price" => 3,
"profit" => 2,
"other" => 1
],
"ab"=>[
"price" => 3,
"profit" => 2,
"other" => 2
]
]
],  
"b"=>[
"content"=>[
"ba"=>[
"price" => 3,
"profit" => 2,
"other" => 4
],
"bb"=>[
"price" => 3,
"profit" => 2,
"other" => 5
]
]
],
]    
];

defineNewValues($myArray, [
"data.*.content.*.price" => 0,
"data.*.content.*.profit" => 0,
]);

print_r($myArray);
/* OUTPUT
Array
(
[data] => Array
(
[a] => Array
(
[content] => Array
(
[aa] => Array
(
[price] => 0
[profit] => 0
[other] => 1
)
[ab] => Array
(
[price] => 0
[profit] => 0
[other] => 2
)
)
)
[b] => Array
(
[content] => Array
(
[ba] => Array
(
[price] => 0
[profit] => 0
[other] => 4
)
[bb] => Array
(
[price] => 0
[profit] => 0
[other] => 5
)
)
)
)
)
*/

因为要替换的键只出现在数据的一个级别上,所以解决方案实际上不需要考虑整个数组结构。你可以把每一个价格和利润键都替换掉。

array_walk_recursive($example, function(&$value, $key) {
if (in_array($key, ['price', 'profit'])) {
$value = 0;
}
});

根据你对另一个答案的评论,我对"正确和专业的方式"的看法;我们应该尽量用最简单的方法来解决问题,因为简单的方法容易维护。

最新更新