Search code examples
phparraysipb

Extract a column value while iterating a query result set and use the value as the first level key in the new 2d array


I am looping over the result set rows of a database query and I want to apply first level keys based on a specific column value. I also wish to remove column being used as keys from each row.

The print_f() of each row:

Array ( [pf_id] => 5 [pf_title] => Gender [pf_icon] => [pf_key] => gender )
Array ( [pf_id] => 6 [pf_title] => Location [pf_icon] => [pf_key] => location )
Array ( [pf_id] => 7 [pf_title] => Interests [pf_icon] => [pf_key] => interests )

Desired result using pf_id as new first level keys:

Array (
 5 => array ([pf_title] => Gender [pf_icon] => [pf_key] => gender)
 6 => array ([pf_title] => Location [pf_icon] => [pf_key] => location)
 7 => array ([pf_title] => Interests [pf_icon] => [pf_key] => interests)
)

My current code to fetch the data:

$cfields = array();
$this->DB->build( array(
    'select' => 'pf_d.pf_id, pf_d.pf_title, pf_d.pf_icon, pf_d.pf_key',
    'from' => array( 'pfields_data' => 'pf_d' ),
    'where' => 'pf_d.pf_id = 5 or pf_d.pf_id = 6 or pf_d.pf_id = 7',
) );

$this->DB->execute();
while ( $row = $this->DB->fetch() ) {
    // array correction starts please help!!
    #                       $extract = array();
    #                       $extract = implode/explode??
    #           $extract[] = $row['pf_id'].' => '.array( 'pf_title' => $row['pf_title'], 'pf_icon' => $row['pf_icon'], 'pf_key' => $row['pf_key']);
    // array correction finish

    $cfields[] = $extract;
    print_r($row);
}

I am using InvisionPowerBoard (I am customer but it not require a their response to solve).


Solution

  • i have solved... I edit while() into

    while ( $row = $this->DB->fetch() ) {
        $b_array = array_slice($row, 1);
        $cfields[ $row['pf_id'] ] = $b_array;
    }
    

    result

    Array
    (
        [5] => Array
            (
                [pf_title] => Gender
                [pf_icon] => 
                [pf_key] => gender
            )
    
        [6] => Array
            (
                [pf_title] => Location
                [pf_icon] => 
                [pf_key] => location
            )
    
        [7] => Array
            (
                [pf_title] => Interests
                [pf_icon] => 
                [pf_key] => interests
            )
    
    )