This question already has an answer here:
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',
)
</div>
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
)
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;
You can accomplish this using following
array_column($array,'post_title','ID');
Output
Array
(
[1] => Hello world!
[79] => ffffffffffff
[1720] => Git primer
)