PHP奇怪的str_split数组输出

时间:2016-03-22 11:34:45

标签: php arrays string multidimensional-array

好的,我有麻烦搞清楚为什么我的str_split给出奇怪的数组输出,这就是代码:

$test = array(0 => array(53, 22, 12, "string"),
            1 => array(94, 84, 94, "string1"),
            2 => array(56, 45, 104, "string2"),
            3 => array(33, 21, 20, 23, "string3"),
            4 => array(44, 55, 66, 77)
            );

$newArray = array();            
$keys = array_keys($test);
for($i=0; $i < count($test); $i++){
foreach($test[$keys[$i]] as $key => $value){
}
$output = str_split($key);

echo "<pre>";
print_r($output);
echo "</pre>";  

数组输出为:

Array
(
[0] => 3
)

Array
(
[0] => 3
)

Array
(
[0] => 3
)

Array
(
[0] => 4
)

Array
(
[0] => 3
)

我期待这样的输出:

Array ([0] => 3
       [1] => 3
       [2] => 3
       [3] => 4
       [4] => 3
      )

我想知道为什么会这样?谢谢。

2 个答案:

答案 0 :(得分:3)

要实现给定的输出,you would just do

<?php

$test = array(0 => array(53, 22, 12, "string"),
        1 => array(94, 84, 94, "string1"),
        2 => array(56, 45, 104, "string2"),
        3 => array(33, 21, 20, 23, "string3"),
        4 => array(44, 55, 66, 77)
        );

foreach ($test as $row) {
    $output[] = count($row)-1;          // non-associative, so the last key is
}                                       // just the length of the array minus 1

print_r($output);

?>

因为子数组不是关联的。

如果是,请用:

替换循环内的行
    $keys = array_keys($row);           // get the keys of the row
    $output[] = $keys[count($keys)-1];  // and access the last of them

答案 1 :(得分:1)

使用您的代码解决方案,但这不是一种有效的方法。

<?php
$test = array(0 => array(53, 22, 12, "string"),
            1 => array(94, 84, 94, "string1"),
            2 => array(56, 45, 104, "string2"),
            3 => array(33, 21, 20, 23, "string3"),
            4 => array(44, 55, 66, 77)
            );

$newArray = array();            
$keys = array_keys($test);
for($i=0; $i < count($test); $i++){
foreach($test[$i] as $key => $value){
    $output[$i] = str_split($key)[0];
}
echo "<pre>";
//print_r($output);
echo "</pre>";  
}
var_dump($output);

输出

array (size=5)
  0 => string '3' (length=1)
  1 => string '3' (length=1)
  2 => string '3' (length=1)
  3 => string '4' (length=1)
  4 => string '3' (length=1)

但是,当字符串位置不恒定时,通过将其更改为可行,对于数组

<?php
$test = array(0 => array(53, 22, 12, "string"),
            1 => array(94, 84, 94, "string1"),
            2 => array(56, 45, 104, "string2"),
            3 => array(33, 21, "string3", 20, 23),
            4 => array(44, 55, 66, 77)
            );



$newArray = array();            
$keys = array_keys($test);
for($i=0; $i < count($test); $i++){
foreach($test[$i] as $key => $value){
    if(is_string($value)){
       unset($test[$i][$key]);
    }
    $output[$i] = count($test[$i]);
}
echo "<pre>";
//print_r($output);
echo "</pre>";  
}
var_dump($output);

输出

array (size=5)
  0 => int 3
  1 => int 3
  2 => int 3
  3 => int 4
  4 => int 4