php - 查找具有特定列值的目标行 - 没有循环
问题描述
$rows
是一个表行数组 - 包含列名和值
需要找到列id
等于变量的行
这是一种使用循环的方法,它可以工作
$id = 5;
foreach($rows as $row){
if($row['id'] == $id){$target = $row;}
}
那么有没有更短的方法 - 没有循环?
像:
$target = $rows[having id = $id]
解决方案
使用array_search
方法和array_column
as:
<?php
// sample data
$rows = array(
array("id" => 1, "title" => "Title 1"),
array("id" => 2, "title" => "Title 2"),
array("id" => 5, "title" => "Title 5")
);
$id = 5; // to find the row with id equals to this
$key = array_search($id, array_column($rows, 'id')); // returns the mathching index or 0 by default
var_dump($rows[$key]);
?>
输出:
array(2) {
["id"]=>
int(5)
["title"]=>
string(7) "Title 5"
}
推荐阅读
- datetime - 在 azure cosmos db 中的两个日期之间选择行
- javascript - 如何改进这个斯诺克得分应用程序?
- javascript - TypeError:无法读取未定义 API 的属性“ft”
- json - 使用 PowerShell 将 JSON 转换为 plist
- html - 跨 2 行垂直对齐长按钮
- ruby - Ruby on rails、Solidus 电子商务、谷歌索引问题
- reactjs - 如何从material-ui延迟渲染选择组件
- html - Selenium VBA 找不到元素
- java - 输出未显示在我的设备上(Android Studio)
- excel - 通过 VBA 在 Excel 中复制单元格公式