-3

I have an Array format.

Array
(
    [0] => Array
        (
            [order_id] => 1
        )

    [1] => Array
        (
            [order_id] => 11
        )

    [2] => Array
        (
            [order_id] => 12
        )

)

It should to be changed the array format to be like this format:

[1,11,12];

Please help. Thank you in advanced.

cocksparrer
  • 219
  • 1
  • 6
  • 17

4 Answers4

3

For (PHP 5 >= 5.5.0, PHP 7) you can use array_column and lower than that you can use array_map function (for PHP < 5.3) you need to define saperate function for array_map instead of anonymous function.

$array = array
(
    '0' => array
    (
        'order_id' => 1
    ),

    '1' => array
    (
        'order_id' => 11
    ),

    '2' => array
    (
        'order_id' => 12
    )

);

$new_array = array_column($array, 'order_id');
print_r($new_array);


$new_array = array_map(function($element) {
    return $element['order_id'];
}, $array);
print_r($new_array);

output

Array
(
    [0] => 1
    [1] => 11
    [2] => 12
)
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
0

How about this?

$arr = Array
(
    0 => Array
        (
            'order_id' => 1
        ),

    1 => Array
        (
            'order_id'=> 11
        ),

   2 => Array
        (
            'order_id' => 12
        ),

);
$newArr = array();

foreach($arr as $x){
    foreach($x as $y){
        $newArr[] = $y;
    }
}
JKidd404
  • 88
  • 6
0

You can try this:

$ar = array(array('order_id' => 1), array('order_id' => 11), array('order_id' => 12));

$temp = array();

foreach ($ar as $val) {
    $temp[] = $val['order_id'];
}

print_r($temp);
Md Mahfuzur Rahman
  • 2,319
  • 2
  • 18
  • 28
0

Basically, you are looking to flatten the array. This SO answer has some tips on how to do that. Also, there's a golf version in this Github gist.

For the specific case in your question, this should do

function specificFlatten($arr) {
    if (!is_array($arr)) return false;

    $result = [];

    foreach ($arr as $arr_1) {
        result[] = $arr_1['order_id'];
    }

    return $result;
}
Community
  • 1
  • 1
Igbanam
  • 5,904
  • 5
  • 44
  • 68