0

After going through similar questions i couldn't find matching my scenario. I have $artists_temp array like

Array
(
    [0] => Array
        (
            [ID] => 109
            [post_title] => Junoon
        )

    [1] => Array
        (
            [ID] => 135
            [post_title] => Linkin Park
        )

)

I have done with code to make the array like

Array
(
    [109] => Junoon
    [Junoon] => 
    [135] => Linkin Park
    [Linkin Park] => 
)

Whats required is like

Array
(
    [109] => Junoon
    [135] => Linkin Park
)

Here is the code

$artists_temp = $wpdb->get_results($query, ARRAY_A);
$artists = array();
foreach ($artists_temp as $key => $value) {
    foreach ($value as $k => $v) {
        $artists[$v] = next($value);
        //unset(next($value)) This doesn't work.
    }
}
print_r($artists);
2
  • 1
    You could add break; on the line after $artists[$v] = . Commented Mar 4, 2015 at 21:19
  • @cpilko Thanks man that did the work ! Commented Mar 4, 2015 at 21:29

2 Answers 2

2

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column():

$artists = array_column($artists_temp, 'post_title', 'ID');

Since you are using WordPress check out: wp_list_pluck():

$artists = wp_list_pluck($artists_temp, 'post_title', 'ID');
Sign up to request clarification or add additional context in comments.

5 Comments

this is informative really. But as i am creating a wordpress plugin not all users have 5.5
I hate WordPress, but a quick search turned-up codex.wordpress.org/Function_Reference/wp_list_pluck
accepted the below answer but thanks for sharing the nice function array_column is so cool !
So you didn't like the WP function that does exactly what you want?
I was more concerned about the solution in terms of programming.
1

You can also do

$artists = array();

foreach ($artists_temp as $array) {
    $artists[$array['ID']] = $array['post_title'];
}

2 Comments

cant wait 1 minute to accept this :) Works like a charm
Glad I could be of service! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.