Backend Development 2 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Extracting Values from a Two-Dimensional PHP Array by ID

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.

BackendPHParrayData Extractionfunction
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.