Extracting Values from a Two-Dimensional PHP Array by ID
This article demonstrates how to create a reusable PHP function that searches a two‑dimensional array for a specific id and returns the value of a given key, such as the title, using a simple loop and conditional check.
In PHP, working with two‑dimensional arrays is common, and sometimes you need to extract a one‑dimensional value based on certain conditions.
Example data:
$arr = [
[
"id" => 1,
"view" => 2,
"category_id" => 2,
"title" => "标题一",
"model" => 12,
"desc" => "摘要",
],
[
"id" => 123,
"view" => 2,
"category_id" => 1,
"title" => "标题二",
"model" => 101,
"desc" => "摘要",
]
];Requirement:
Extract the sub‑array whose id is 123 and obtain the value of a specific key (e.g., "title" ).
Solution:
We can create a function getval to achieve this:
function getval($arr, $id, $key){
foreach ($arr as $v){
if($v['id'] == $id){
return $v[$key];
}
}
}The function accepts three parameters:
$arr : the two‑dimensional array to search.
$id : the id value to match.
$key : the key whose value should be returned.
Usage example:
$title = getVal($arr, 123, 'title');
var_dump($title); // string(9) "标题二"By calling getval , you can retrieve the desired data based on the id and key.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.