将多维数组键转换为字符串

时间:2014-09-17 11:49:27

标签: php arrays multidimensional-array

我有一个像这样的多维数组:

$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';

另一个数组如:

$array2['second-first']='newvalue21';
$array2['second-third-first']='newvalue231';

我无法以递归的方式行走$array1,以便在每次迭代中检查$array2中是否存在任何元素,其中一个键等效于当前元素键,并将其父元素转换​​为字符串。

为了简化这个问题,我将拥有足够的功能,可以输出如下内容:

// walking $array1:
first
second-first
second-second
second-third-first
second-fourth
third

谢谢。

基于ClémentMalet的解决方案

function print_array_reccur ($array1, $array2, $str = '') 
{
    foreach ($array1 as $key => $val) {
        if (is_array($val)) {
            if ($str == '') {
                print_array_reccur($val, $array2, $key);
            } else {
                print_array_reccur($val, $array2, $str . '-' . $key);
            }
        } else {
            if ($str == '') {
                $result = $key;
            } else {
                $result = $str . '-' . $key;
            }
            if(isset($array2[$result]))
            {
                echo 'Found $array2['.$result.'] = ' . $array2[$result] . "\n";
            }
        }
    }
}

print_array_reccur ($array1, $array2);

/* OUTPUT:
Found $array2[second-first] = newvalue21
Found $array2[second-third-first] = newvalue231
*/

1 个答案:

答案 0 :(得分:1)

我真的不明白你最想要的是什么,以及你希望以后用你的第二个阵列实现的目标。

但是既然你正在寻找一种打印东西的方法(很高兴你简化了这种方式),这里是:

$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';

function print_array_reccur ($array, $str = '') {

  foreach ($array as $key => $val) {
    if (is_array($val)) {
      if ($str == '') {
        print_array_reccur($val, $key);
      } else {
        print_array_reccur($val, $str . '-' . $key);
      }
    } else {
      if ($str == '') {
        echo $key . "\n";
      } else {
        echo $str . '-' . $key . "\n";
      }
    }
  }

}

print_array_reccur ($array1);

输出:

first
second-first
second-second
second-third-first
second-fourth
third