排序嵌套数组php

时间:2016-03-21 08:57:32

标签: php arrays multidimensional-array

这是我的阵列,我想在一个阵列中使用60,20,39,70,12,29,31,72,59。一维数组。

$marks = array(
    "abc" => array(
    "a" => 60,
    "b" => 20,
    "c" => 39
    ),
    "def" => array(
    "a" => 70,
    "b" => 12,
    "c" => 29
    ),
    "xyz" => array(
    "a" => 31,
    "b" => 72,
    "c" => 59
    )
 );

我的尝试是

foreach($marks as $name=>$score)
{
   foreach($score as $subject=>$number)
     { 
$array[]= $number;
    } 

}

但是当我打印这个数组时,它再次生成三个数组。 on print_r($ array);它显示了这个输出。

Array ( [0] => 60 [1] => 20 [2] => 39 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 [6] => 31 [7] => 72 [8] => 59 )

有没有任何方法可以从上面的数组中获取最后一个数组。或任何其他解决方案。

5 个答案:

答案 0 :(得分:1)

尝试这样来展平数组:

iframe

输出:

<?php

$marks = array(
    "abc" => array(
    "a" => 60,
    "b" => 20,
    "c" => 39
    ),
    "def" => array(
    "a" => 70,
    "b" => 12,
    "c" => 29
    ),
    "xyz" => array(
    "a" => 31,
    "b" => 72,
    "c" => 59
    )
 );

function array_values_recursive($array)
{
    $arrayValues = array();

    foreach ($array as $value)
    {
        if (is_scalar($value) OR is_resource($value))
        {
             $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
             $arrayValues = array_merge($arrayValues, array_values_recursive($value));
        }
    }

    return $arrayValues;
}

 var_dump(array_values_recursive($marks));

此自定义功能取自:http://php.net/manual/en/function.array-values.php

答案 1 :(得分:1)

你可以用传统的方式,即foreach循环,也可以使用迭代器。看看下面的解决方案:

1)使用foreach循环和array_merge函数

$marks = array(
    "abc" => array(
        "a" => 60,
        "b" => 20,
        "c" => 39
    ),
    "def" => array(
        "a" => 70,
        "b" => 12,
        "c" => 29
    ),
    "xyz" => array(
        "a" => 31,
        "b" => 72,
        "c" => 59
    )
);

$new_array = array();
foreach ($marks as $mark) {
    $new_array = array_merge($new_array, array_values($mark));
}

print_r($new_array);

2)使用ArrayIterator

$new_array = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($marks));
foreach ($iterator as $key => $value) {
    $new_array[] = $value;
}

print_r($new_array);

在两个解决方案中输出将是:

Array
(
    [0] => 60
    [1] => 20
    [2] => 39
    [3] => 70
    [4] => 12
    [5] => 29
    [6] => 31
    [7] => 72
    [8] => 59
)

答案 2 :(得分:0)

因为您要在第一个$array循环中转储foreach:)

答案 3 :(得分:0)

你的声音就像你可能在for循环中声明你的$数组一样,如果你这样做,你会得到三个数组。所以在for循环之外声明将获得单个数组

$array = array(); //correct
foreach($marks as $name=>$score)
{
//$array = array(); //incorrect
 foreach($score as $subject=>$number)
 { 
   $array[]= $number;
 }
}
var_dump($array);

答案 4 :(得分:0)

foreach($marks as $name=>$score)
{
    foreach($score as $subject=>$number)
    { 
        $array[]= $number;
    }
}