Sapp
Sapp

Reputation: 654

Query result array modifying

I got the following array , as a result from the MySQL query:

Array
(
    [0] => Array
        (
            [id] => 11
            [owner] => Mark
        )

    [1] => Array
        (
            [id] => 10
            [owner] => David
        )

    [2] => Array
        (
            [id] => 9
            [owner] => Poul
        )

    [3] => Array
        (
            [id] => 8
            [owner] => Peter
        )

    [4] => Array
        (
            [id] => 7
            [owner] => Peter
        )

    [5] => Array
        (
            [id] => 6
            [owner] => Lucas
        )

)

Is there a way to modify it, using the PHP functions and ommit the foreach process?

I would like it to look following:

Array
(
    11 => Mark
    10 => David
    9 => Poul
    8 => Peter
    7 => Peter
    6 => Lucas
)

So , basicly it should build this array from the id and the owner values. Like id => owner.

Is that possible?

Upvotes: 1

Views: 98

Answers (2)

If your original array is $arr then the following code would alter it as you want:

$tot = count($arr);
for($i=0;$i<$tot;$i++) {
   $key = $arr[$i]['id'];
   $val = $arr[$i]['owner'];
   unset($arr[$i]);
   $arr[$key] = $val;
}

Upvotes: 0

kgarthai
kgarthai

Reputation: 100

If you're using PDO, you can do something like this:

$stmt = $dbh->query("SELECT id, owner FROM table");
$arr = $stmt->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);

This should give you an array, where the indices of the array are the values of the first column in your result, namely id.

Upvotes: 2

Related Questions