-1

If I have a multidimensional array, and I want to extract some of the data from it and place them in a new array, is there any existing array_*() function to do so?

For example, if I have the following array:

array(
    [
        'id'    => 1,
        'num'   => 200,
        'text'  => 'abc'
    ],
    [
        'id'    => 2,
        'num'   => 230,
        'text'  => 'def'
    ],
    [
        'id'    => 3,
        'num'   => 100,
        'text'  => 'ghi'
    ],

)

I would like to get the following resulting array:

[ 'abc', 'def', 'ghi' ]

Of course I can always do it manually using foreach() or something similar, but one-liners are always nice :)

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • 1
    Use `array_column($array, 'text');` with out use of foreach loop http://php.net/manual/en/function.array-column.php – Saty Mar 22 '17 at 05:16
  • 1
    In fact your question is a perfect use case for `array_column`. Manual almost has the same example there http://php.net/array_column – Hanky Panky Mar 22 '17 at 05:18

2 Answers2

2

Try array_column function;

array_column(array $data, 'key')
Basant Rules
  • 785
  • 11
  • 8
0

You may use array_map() in php

<?php
    $array = array([
            'id'    => 1,
            'num'   => 200,
            'text'  => 'abc'
        ],
        [
            'id'    => 2,
            'num'   => 230,
            'text'  => 'def'
        ],
        [
            'id'    => 3,
            'num'   => 100,
            'text'  => 'ghi'
        ],

    );


    $return = array_map(function ($value) {
        return  $value['text'];
    }, $array);

    echo "<pre>"; 
    print_R($return);
    ?>
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40