Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.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_Arrays - Fatal编程技术网

Php 使用属性作为键将常规数组转换为关联数组的最佳实践?

Php 使用属性作为键将常规数组转换为关联数组的最佳实践?,php,arrays,Php,Arrays,假设我有以下数组 [ { "id": "16", "name": "dog", }, { "id": "17", "name": "cat", }, { "id": "18", "name": "mouse", } ] 我想使用一个特定属性,id作为数组的键

假设我有以下数组

[
        {
            "id": "16",
            "name": "dog",
        },
        {
            "id": "17",
            "name": "cat",
        },
        {
            "id": "18",
            "name": "mouse",
        }
]
我想使用一个特定属性,
id
作为数组的键。我可以这样做:

$someArray = [
    ["id" => "16", "name" => "dog"],
    ["id" => "17", "name" => "cat"],
    ["id" => "18", "name" => "mouse"]
];


$newArray = [];
foreach ($someArray as $currItem)
{
    $newArray[$currItem["id"]] = $currItem;
}
然后我会得到这个(期望的结果)


我的问题是:有没有更好的方法?我真的需要循环每一项来重新定义我的数组吗?

我似乎已经找到了一个解决方案,它使用了Rizier123的评论和以下线程中的信息:

据我所知,
array\u column
只会给我一个id数组,所以我需要将它与
array\u combine
array\u值一起使用。如果你有更好的答案,请不要害怕发帖

$someArray = [
    ["id" => "16", "name" => "a"],
    ["id" => "17", "name" => "b"],
    ["id" => "18", "name" => "c"]
];


$newArray =  array_combine(array_column($someArray, "id"), $someArray);

你抢先找到了答案,但我还是可以贡献一点

我不确定原始数组来自何处,但如果您正在解码JSON,则可以提供第二个参数来强制将对象转换为关联数组

$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents, TRUE); // note the second parameter
$v = array_combine(array_column($arr, "id"), $arr); 
var_dump($v);
编辑: 如果您可以容忍输出数组具有对象,则这也可能会起作用:

$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
        array_column(
                array_map(
                        function($item) { return (array)$item; },
                        $arr 
                ),
                "id"
        ),
        $arr
);
var_dump($v);

请记住,对于非常大的阵列,性能可能会成为一个问题。这是在做大量的数组搜索。

如果你愿意,你可以使用
array\u column()只需执行
array\u列($someArray,NULL,“id”)
谢谢,我相信有人会觉得这很有帮助。不过,我只是将其显示为json,以使其更易于阅读。它实际上来自MySQL数据库根据您的MySQL数据库访问方法,您可以将db记录作为数组而不是对象返回——或者简单地将它们转换为$arr=(array)$db_objectI我使用PDO,我知道PDO::FETCH_ASSOC,但我不知道是否可以将id作为键?我使用
$results=$query->fetchAll(PDO::FETCH_ASSOC)PDO::FETCH\u ASSOC:返回一个按列名索引的数组,该数组在结果集中返回。
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
        array_column(
                array_map(
                        function($item) { return (array)$item; },
                        $arr 
                ),
                "id"
        ),
        $arr
);
var_dump($v);