0

I have the following array structure

array (
  0 => 
  array (
    'ID' => '1',
    'post_title' => 'Hello world!',
  ),
  1 => 
  array (
    'ID' => '79',
    'post_title' => 'ffffffffffff',
  ),
  2 => 
  array (
    'ID' => '1720',
    'post_title' => 'Git primer',
  ),
)

I will love to convert it to a structure similar to the one below. Is there any php function that can do this? I am trying to avoid repetitive foreach loop.

array (
'1' => 'Hello world!',
'79' => 'ffffffffffff',
'1720' => 'Git primer',
)
W3Guy
  • 657
  • 1
  • 7
  • 16
  • 2
    a simple foreach + `$new_array[$v['ID']] = $v['post_title'];` why in the world wouldn't you want a foreach, it'll just take less than 4 lines – Kevin Aug 05 '16 at 05:17
  • I will repeat my comment from yesterday: http://stackoverflow.com/questions/38750886/php-mapping-a-multi-dimensional-into-an-associative-array#comment64875556_38750886 – Rizier123 Aug 05 '16 at 05:24

3 Answers3

4

Use array_column()to get this.

Array_column() function return all column name you have specify in parameter.

$array=array (
  0 => 
  array (
    'ID' => '1',
    'post_title' => 'Hello world!',
  ),
  1 => 
  array (
    'ID' => '79',
    'post_title' => 'ffffffffffff',
  ),
  2 => 
  array (
    'ID' => '1720',
    'post_title' => 'Git primer',
  ),
)
$new_array = array_column($array, 'post_title', 'ID');
print_r($new_array);

Output:

Array
(
    [1] => Hello world!
    [79] => ffffffffffff
    [1720] => Git primer
)
Kevin
  • 41,694
  • 12
  • 53
  • 70
Nikhil Vaghela
  • 2,088
  • 2
  • 15
  • 30
0

Here it is:

//Your array

$test = array (
  0 => 
  array (
    'ID' => '1',
    'post_title' => 'Hello world!',
  ),
  1 => 
  array (
    'ID' => '79',
    'post_title' => 'ffffffffffff',
  ),
  2 => 
  array (
    'ID' => '1720',
    'post_title' => 'Git primer',
  ),
);

//Solution:

foreach ($test as $t){
    $new_array[$t['ID']] = $t['post_title'];

}
echo "<pre>";
echo print_r($new_array);
die;
Maha Dev
  • 3,915
  • 2
  • 31
  • 50
0

You can accomplish this using following

array_column($array,'post_title','ID');

Output

Array
(
    [1] => Hello world!
    [79] => ffffffffffff
    [1720] => Git primer
)
Saurabh
  • 776
  • 1
  • 5
  • 15