-2

I have an array which consist monthly information as shown below :

[appr] => Array
            (
                [0] => Array
                    (
                        [month] => August
                        [approd] => 23
                    )

                [1] => Array
                    (
                        [month] => September
                        [approd] => 546
                    )

                [2] => Array
                    (
                        [month] => October
                        [approd] => 234
                    )

            )

I want the output as below

[appr] => Array(
        August => 23,
        September => 546,
        October => 234
   )

can anybody help me to achieve this using php.

Madhuri
  • 23
  • 1
  • 8

4 Answers4

2

If you're looking for a simple one-liner solution, use array_column() and array_combine() functions.

Try this:

$array['appr'] = array_combine(array_column($array['appr'], "month"), array_column($array['appr'], "approd"));
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
2

Simply loop in your array and create a new array

$array = array(array('month'=>'August','approd'=>'23'),array('month'=>'September','approd'=>'56'),array('month'=>'October','approd'=>'234'),);
$new = array();
foreach($array as $val) {
   $new['appr'][$val['month']] = $val['approd'];
}
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
1

"One-line" solution using array_column function:

$arr['appr'] = array_column($arr['appr'], 'approd', 'month');

print_r($arr);

The output:

Array
(
    [appr] => Array
        (
            [August] => 23
            [September] => 546
            [October] => 234
        )
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

Another option is to use array_walk_recursive:

<?php

$array = array(
    0 => array(
        'something',
    ),
    1 => array(
        'else',
    )
);


// If the keys are unique
$newArray = array();
array_walk_recursive($array, function($v, $k) use (&$newArray) {
    $newArray[$k] = $v;
});

// If you have duplicate keys
$newArray = array();
array_walk_recursive($array, function($v) use (&$newArray) {
    $newArray[] = $v;
});

And finally output the result:

print_r($newArray);

Resources

Peter
  • 8,776
  • 6
  • 62
  • 95