0

I have an array like

$my_array = Array
(
    [0] => Array
        (
            [0] => rock
        )

    [1] => Array
        (
            [1] => James
        )

     [2] => Array
        (
            [2] => John
        )
)

and I want array like this

array([0]=>rock [1]=>James [2]=> john);

I could get the array in this form. Please help me.

Raghbendra Nayak
  • 1,606
  • 3
  • 22
  • 47
user3056158
  • 707
  • 2
  • 13
  • 20
  • Why you are creating this type of array? Direct create as u want – Keyur Mistry Nov 11 '16 at 09:33
  • Does the array really look like this? I'd expect both James and John to have an index of 0. If they are 0, then [array_column()](http://php.net/array_column) should give you what you want. – Jonnix Nov 11 '16 at 09:34

4 Answers4

1

Your array child contains the same key as the parent arrays, so you must use same keys for both!

$my_array = array(
      array( '0' => 'rock' ),
      array( '1' => 'James' ),
      array( '2' => 'John')
);

This will work:

$n_a = [];
foreach($my_array $k => $ma) {
     $n_a[$k] = $ma[$k]; //here is the problem
}
print_r($n_a);

$n_a contains final array.

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
1

You can achieve that by a single line of code:

Using call_user_func_array() with array_merge(),

$final_array = call_user_func_array('array_merge', $array);
viral
  • 3,724
  • 1
  • 18
  • 32
0

Here is a solution:

$newArray = [];
foreach ($data as $value) {
    $newArray[] = $value[0];
}

$newArray will hold the new array result

krasipenkov
  • 2,031
  • 1
  • 11
  • 13
0

Use foreach like this

$my_array = array
(
array
    (
        '0' => 'rock'
    )
,
array
    (
        '1' => 'James'
    )
,
 array
    (
        '2' => 'John'
    )
);
print_r($my_array);

$newArray = [];
foreach ($my_array as $key => $value) {
    $newArray[] = $value[$key];
}
print_r($newArray);
Aman Rawat
  • 2,625
  • 1
  • 25
  • 40