递归地遍历PHP数组来操作数据


Recursively loop through a PHP array to manipulate data

我试图通过PHP数组循环,但我只得到我的原始数据。我想这和我何时打破循环

有关
$newData = $this->seperateKeyValuePairs($data);
private function seperateKeyValuePairs($array)
{
    foreach($array as $key => $item)
    {
      if( is_array($item) ) $this->seperateKeyValuePairs($item);
      if( is_string($key) && $this->stringStartsWith($key, 'is_') ) {
        $item = $this->makeBoolean($item);
      }
    }
    return $array;
}

我认为问题出在这一行:

$item = $this->makeBoolean($item);

修改item的值。Item不是指向数组中值的指针,而是它的副本,因此数组中的值保持不变。你需要做的是:

$array[$key] = $this->makeBoolean($item);

同样地,你必须改变

if( is_array($item) ) $this->seperateKeyValuePairs($item);

if( is_array($item) ) $array[$key] = $this->seperateKeyValuePairs($item);