Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 查询结果数组修改_Php_Mysql_Arrays_Pdo - Fatal编程技术网

Php 查询结果数组修改

Php 查询结果数组修改,php,mysql,arrays,pdo,Php,Mysql,Arrays,Pdo,通过MySQL查询,我得到了以下数组: Array ( [0] => Array ( [id] => 11 [owner] => Mark ) [1] => Array ( [id] => 10 [owner] => David ) [2] => Array

通过MySQL查询,我得到了以下数组:

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
        )

)
有没有办法修改它,使用PHP函数和ommit
foreach
过程

我希望它如下所示:

Array
(
    11 => Mark
    10 => David
    9 => Poul
    8 => Peter
    7 => Peter
    6 => Lucas
)
因此,它基本上应该从
id
owner
值构建这个数组。比如
id=>owner


这可能吗?

如果您使用PDO,可以执行以下操作:

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

这将为您提供一个数组,其中数组的索引是结果中第一列的值,即id。

如果原始数组是
$arr
,则以下代码将根据您的需要对其进行更改:

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

对于($i=0;$i使用魔法太少了,我不可能知道怎么做。听起来很完美!你会怎么做,使用魔法?魔术师永远不会泄露他的秘密:说出泄露的秘密,也许SQL代码会有用,为了解决这个问题…只需使用
foreach
。你为什么要做变通?