1

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?

6
  • Short of using magic, I can't possibly see how. Commented Sep 12, 2012 at 23:24
  • 1
    That sounds perfect! How would you do it, using magic? Commented Sep 12, 2012 at 23:25
  • 1
    A magician never reveals his secret :P Commented Sep 12, 2012 at 23:25
  • Speaking of revealed secrets, perhaps the SQL code would be of use, to solve this... Commented Sep 12, 2012 at 23:26
  • Just use foreach. Why you want to make workaround? Commented Sep 12, 2012 at 23:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.