首页 > 解决方案 > 具有特定键值对的搜索数组

问题描述

假设我在 php 中有这个数组列表

[
  {
    "id": "1",
    "name": "test1",
  },
  {
    "id": "2",
    "name": "test2",
  },
]

如何轻松返回 name=test1 的 id?

标签: phparrayslist

解决方案


尝试使用array_search(). 首先,获取id、name对的位置,然后获取id字段的内容。

//Get the key of the 'id, name' pair
$key = array_search('test2', array_column($input, 'name'));

//Get the id beloning to the name
$id = $input[$key]->id; 

这里是一个工作示例。


推荐阅读