gpt4 book ai didi

php - 更改 array_walk 函数中的数组键?

转载 作者:IT王子 更新时间:2023-10-28 23:46:37 24 4
gpt4 key购买 nike

我正在使用数组函数将竖线分隔的字符串转换为关联数组。

$piper = "|k=f|p=t|e=r|t=m|";

$piper = explode("|",$piper);

$piper = array_filter($piper);

function splitter(&$value,$key) {

$splitted = explode("=",$value);
$key = $splitted[0];
$value = $splitted[1];

}

array_walk($piper, 'splitter');

var_dump($piper);

这给了我

array (size=4)
1 => string 'f' (length=1)
2 => string 't' (length=1)
3 => string 'r' (length=1)
4 => string 'm' (length=1)

我想要的地方:

array (size=4)
"k" => string 'f' (length=1)
"p" => string 't' (length=1)
"e" => string 'r' (length=1)
"t" => string 'm' (length=1)

但 key 没有改变。是否有任何数组函数可以让我循环遍历数组并更改键和值?

最佳答案

array_walk的文档中说(描述回调函数):

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

这意味着您不能使用 array_walk 来更改迭代数组的键。但是,您可以使用它创建一个新数组:

$result = array();
array_walk($piper, function (&$value,$key) use (&$result) {
$splitted = explode("=",$value);
$result[ $splitted[0] ] = $splitted[1];
});
var_dump($result);

不过,我认为如果是我,我会在这里使用正则表达式(而不是“分解分解”):

$piper = "|k=f|p=t|e=r|t=m|";
preg_match_all('#([^=|]*)=([^|]*)#', $piper, $matches, PREG_PATTERN_ORDER);
$piper = array_combine($matches[1], $matches[2]);
var_dump($piper);

关于php - 更改 array_walk 函数中的数组键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com