将数组键及其值拆分为新变量

时间:2014-07-09 04:54:14

标签: php arrays

我完全不知道编程术语,但我有很多像这样的数组

$arr[3][4][0]='sample value A';
$arr[3][4][1]='sample value B';
...and so on

他们每个都有3个键,所以我想知道PHP是否有任何功能可以分成每个var的值,键和细节,如下所示:

$keyA[0]=3;
$keyB[0]=4;
$keyC[0]=0;
$strg[0]='sample value A';

$keyA[1]=3;
$keyB[1]=4;
$keyC[1]=1;
$strg[1]='sample value B';

foreach内没有foreach来抓取值?

2 个答案:

答案 0 :(得分:3)

尝试使用foreach()不知道任何功能可以帮助

foreach($a as $k=> $v) {
  foreach($v as $k1=> $v1) {
       foreach($v1 as $k2=> $v2) {
        $keyA[] = $k;
        $keyB[] = $k1;
        $keyC[] = $k2;
        $strg[] = $v2;
      }
  }
}

print_r($keyA); //Array ( [0] => 3 [1] => 3 )
print_r($keyB); //Array ( [0] => 4 [1] => 4 ) 
print_r($keyC); //Array ( [0] => 0 [1] => 1 ) 
print_r($strg); //Array ( [0] => sample value A [1] => sample value B ) 

答案 1 :(得分:1)

$array[3][4][0] = 'sample value A';
$array[3][4][1] = 'sample value B';

$iter = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($iter as $key => $value) {
    $keys[$iter->getDepth()] = $key;    
    if(!$iter->callHasChildren()) {
        $keyA[] = $keys[0];
        $keyB[] = $keys[1];
        $keyC[] = $keys[2];
        $strg[] = $value;
    }
}

print_r($keyA);
print_r($keyB);
print_r($keyC);
print_r($strg);