php - 具有特定键值对的搜索数组
问题描述
假设我在 php 中有这个数组列表
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
},
]
如何轻松返回 name=test1 的 id?
解决方案
尝试使用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;
这里是一个工作示例。
推荐阅读
- python - 使用熊猫我从一组表中得到是和否,但我想从中提取是和否
- javascript - React-Redux 将元素添加到列表会导致所有元素的渲染
- single-sign-on - 从所有客户端注销身份服务器 4 不起作用
- python - 如何将不同“列”的列表热编码到数据帧
- sql - 如何将查询的不同结果从一个表连接到存储过程中的另一个表
- browser - 停止代码和框以更新每个按键的预览
- confluent-kafka-dotnet - 以编程方式验证 Confluent Kafka 访问权限
- mysql - 检查 UNIQUE CONSTRAINT 时是否会截断值?
- vega-lite - 不确定如何使用 Vega-Lite 图表示例 - 似乎是部分代码
- graphql - graphql - 将项目添加到“错误”数组,同时仍返回数据