在array_walk函数中更改数组键?

mit*_*esh 23 php arrays function

我使用数组函数将我的管道分隔字符串转换为关联数组.

$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);
Run Code Online (Sandbox Code Playgroud)

这给了我

array (size=4)
  1 => string 'f' (length=1)
  2 => string 't' (length=1)
  3 => string 'r' (length=1)
  4 => string 'm' (length=1)
Run Code Online (Sandbox Code Playgroud)

我想要的地方:

array (size=4)
  "k" => string 'f' (length=1)
  "p" => string 't' (length=1)
  "e" => string 'r' (length=1)
  "t" => string 'm' (length=1)
Run Code Online (Sandbox Code Playgroud)

但钥匙没有变化.是否有任何数组函数,我可以循环数组并更改键和值?

rai*_*7ow 57

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

只有数组的值可能会改变; 它的结构不能改变,即程序员不能添加,取消设置或重新排序元素.如果回调不符合此要求,则此函数的行为未定义且不可预测.

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

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

不过,我认为如果是我,我会在这里使用正则表达式(而不是"爆炸爆炸"):

$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);
Run Code Online (Sandbox Code Playgroud)

  • 为'使用'+1.提醒一下,这需要PHP 5.3+. (3认同)
  • @AlexandruMihai你会错过这样一个事实:'explode'会被调用多次,因为这里有'k = v'标记,这使它比单个`preg_match_all`调用更昂贵.并且"通常"是在优化讨论中使用的可怕词. (2认同)