Home > database >  Need help to convert Associative Array to key=>value pair
Need help to convert Associative Array to key=>value pair

Time:02-17

My Code:


    global $wpdb;
    $row = $wpdb->get_results( "SELECT * FROM `wp_employee`", ARRAY_A );
    print_r ($row);

Output:

    Array(
    [0] => Array(
        [job_id] => 1
        [job_position] => Architect
        )
    [1] => Array(
        [job_id] => 2
        [job_position] => Civil Engineer
        )
    [2] => Array(
        [job_id] => 3
        [job_position] => Electrical Engineer
        )
    [3] => Array(
        [job_id] => 4
        [job_position] => Plumbing Engineer
        )
    [4] => Array(
        [job_id] => 5
        [job_position] => Site Engineer
        )
    )

Output I need is the following:

    array(
        '1' => 'Architect',
        '2' => 'Civil Engineer',
        '3' => 'Electrical Engineer',
        '4' => 'Plumbing Engineer',
        '5' => 'Site Engineer'
    )

I am still learning, could not figure it our myself. Thank you in advance for helping me out

CodePudding user response:

$array = [
    [ 'job_id' => 1, 'job_position' => 'Architect' ],
    [ 'job_id' => 2, 'job_position' => 'Civil Engineer' ],
    [ 'job_id' => 3, 'job_position' => 'Electrical Engineer' ],
    [ 'job_id' => 4, 'job_position' => 'Plumbing Engineer' ],
    [ 'job_id' => 5, 'job_position' => 'Site Engineer' ]
];

$result = array_column($array, 'job_position', 'job_id');

print_r($result);

Output:

Array
(
    [1] => Architect
    [2] => Civil Engineer
    [3] => Electrical Engineer
    [4] => Plumbing Engineer
    [5] => Site Engineer
)
  • Related