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)我想值得一试。除了整体结果数组外,DB层通常可以将每个记录作为数字索引数组、关联索引数组(键对应于DB列)或属性对应于DB列的对象返回。可能值得玩弄数据库获取语句。或者您可以使用array\u map或array\u walk来执行某种类型的强制转换。@Keatinge,来自“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);