-2

want to convert an array into giving example above in PHP

I have this array

Array
(
    [0] => Array
        (
            [101] => Abbottabad
        )
    [1] => Array
        (
            [102] => Abdul Hakim
        )

    [2] => Array
        (
            [103] => Ahmed Pur East
        )

)

Want to achieve this

Array
(
    [101] => Abbottabad
    [102] => Abdul Hakim
    [103] => Ahmed Pur East
)
Ali abbas
  • 17
  • 4

3 Answers3

1

You can use two loops to iterate to the main array and then the sub arrays where you will be keeping track of the keys and values. Given that the name of your array is $arr:

$new_arr = array();

foreach($arr as $subarr) {
    foreach($subarr as $key => $value) {
        $new_arr[$key] = $value;
    }
}
Omari Celestine
  • 1,405
  • 1
  • 11
  • 21
1

Of if you don't like the look of loops:

$array = array(array(101=>'Abbottabad'),array(102=>'Abdul Hakim'),array(103=>'Ahmed Pur East'));
$merged_array = call_user_func_array('array_merge',$array);
print_r($merged_array);

/* Result
Array
(
    [0] => Abbottabad
    [1] => Abdul Hakim
    [2] => Ahmed Pur East
)
*/
YTZ
  • 876
  • 11
  • 26
  • thanks for the answer but I want it like this Array ( [101] => Abbottabad [102] => Abdul Hakim [103] => Ahmed Pur East ) – Ali abbas Jul 04 '19 at 14:41
1

As your example data contains only a single item per array, you might make use of key and reset inside a foreach loop.

  • key Returns the index element of the current array position
  • reset Returns the value of the first array element

For example:

$arrays = [
    [101 => "Abbottabad"],
    [102 => "Abdul Hakim"],
    [103 => "Ahmed Pur East"]
];

$res = [];

foreach($arrays as $array) {
    $res[key($array)] = reset($array);
}

print_r($res);

Result

Array
(
    [101] => Abbottabad
    [102] => Abdul Hakim
    [103] => Ahmed Pur East
)

Php demo

Note Array keys have to be unique.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70