Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

php - How to Get title by id in 2D array?

I have an array,

array
(
    [0] => array
    (
        [id]       => 2
        [title]    => Test
        [alt_text] => 'This is test',

    )

    [1] => array
    (
        [id]       => 3
        [title]    => Test1
        [alt_text] => 'This is test1',

    )

    [2] => array
    (
        [id]       => 7
        [title]    => Test2
        [alt_text] => "This is test2",

    ),

)

I want the value of the title for dynamic id.

E.g. If I pass 2, then it should return value of title as Test

I can do this with foreach loop no issue. But is there any core function to achieve this or a combination of core functions or a one-liner snippet?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming that your ids are unique (!), you could simply use an associative array instead:

$yourArrray = array(
    2 => array('title' => 'Test', 'alt_text' => 'This is test'),
    3 => array('title' => 'Test1', 'alt_text' => 'This is test1'),
    7 => array('title' => 'Test2', 'alt_text' => 'This is test2')
);

This way, your lookup would be as easy as:

$yourArray[$id]['title']

For example:

$title = $yourArray[2]['title'] // $title Now contains "Test"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...