首页 > 解决方案 > 查找具有特定列值的目标行 - 没有循环

问题描述

$rows是一个表行数组 - 包含列名和值
需要找到列id等于变量的行
这是一种使用循环的方法,它可以工作

$id = 5;

foreach($rows as $row){
    if($row['id'] == $id){$target = $row;}
}

那么有没有更短的方法 - 没有循环?
像:

$target = $rows[having id = $id] 

标签: php

解决方案


使用array_search方法和array_columnas:

<?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"
}

推荐阅读