PHP通过键将多维数组转换为单维数组

时间:2018-01-08 05:27:12

标签: php arrays

阵列:

Array
(
    [0] => Array
        (
            [ID] => 11,
            [Create_date] => 2017-11-23
        ),

    [1] => Array
        (
            [ID] => 10,
            [Create_date] => 2017-11-23
        ),

    [2] => Array
        (
            [ID] => 9,
            [Create_date] => 2017-11-23
        ),

    [3] => Array
        (
            [ID] => 8,
            [Create_date] => 2017-11-23
        ),

    [4] => Array
        (
            [ID] => 7,
            [Create_date] => 2017-11-23
        )

);

预期数组:

array('11','10','9','8', '7');

我知道如何通过使用循环来实现这一结果但是为了提高性能,我们希望使用内置函数,任何人都可以告诉我们如何实现这一结果?

4 个答案:

答案 0 :(得分:4)

在php

中简单使用array_column() Function
$array = [

[
    "ID" => 11,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 10,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 9,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 8,
    "Create_date" => "2017-11-23"
], 
];

echo "<pre>";
print_r(array_column($array, "ID"));
?>

答案 1 :(得分:0)

使用foreach

foreach ($array as $key=>$value)
{
    echo $key.'<br/>';

    echo $value['id'].'<br/>';
    echo $value['Create_date'].'<br/>';
}

答案 2 :(得分:0)

简单 array_map 功能使用。

<?php

    $movies = array(
      array(
        "id" => 11,
        "Create_date" => 2017-11-23,

      ),
      array(
        "id" => 10,
        "Create_date" => 2017-11-23,

      ),
      array(
         "id" => 9,
        "Create_date" => 2017-11-23,

      ),
        array(
         "id" => 8,
        "Create_date" => 2017-11-23,

      ),
       array(
         "id" => 7,
        "Create_date" => 2017-11-23,

      )
    );

    $oneDimensionalArray = array_map('current', $movies);
    print_r($oneDimensionalArray);
    ?>

输出

Array ( [0] => 11 [1] => 10 [2] => 9 [3] => 8 [4] => 7 )

答案 3 :(得分:0)

$array = [
[
    "ID" => 11,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 10,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 9,
    "Create_date" => "2017-11-23"
], 
[
    "ID" => 8,
    "Create_date" => "2017-11-23"
], 
];

foreach ($array as $key=>$value)
{    
    $id[]          =  $value['id'];
    $creatteDate[] = $value['Create_date'];
}

echo "<pre>"; print_r($creatteDate); 

print_r($id); 

exit;