PHP multidimensional array search by value

Ask a question+
0

I have an Array which have multidimensional values
Following is tags array

Array
(
    [0] => Array
        (
            [id] => 10
            [name] => Fibroidsssssssssssss
            [created_at] => 2020-02-17 11:30:11
            [updated_at] => 2020-03-24 15:00:20
        )

    [1] => Array
        (
            [id] => 21
            [name] => Laparoscopic Myomectomy for Fibroids
            [created_at] => 2020-02-17 11:30:11
            [updated_at] => -0001-11-30 00:00:00
        )

    [2] => Array
        (
            [id] => 46
            [name] => Ear reshaping
            [created_at] => 2020-02-17 11:33:28
            [updated_at] => -0001-11-30 00:00:00
        )
)

I want to fetch the tag name if I have a tag id

add comment

1 Answer

1

After looking through the list of PHP Array Functions, I don’t think that there is anything simpler than just running through the array in a loop and checking:

<?php

$tagArray = Array(
    Array("id" => 10, "name" => "Fibroidsssssssssssss", "created_at" => "2020-02-17 11:30:11", "updated_at" => "2020-03-24 15:00:20"),
    Array("id" => 21, "name" => "Laparoscopic Myomectomy for Fibroids", "created_at" => "2020-02-17 11:30:11", "updated_at" => "-0001-11-30 00:00:00"),
    Array("id" => 46, "name" => "Ear reshaping", "created_at" => "2020-02-17 11:33:28", "updated_at" => "-0001-11-30 00:00:00")
);


function GetTagName($arr, $id) {
    foreach ($arr as $i) {
        if ($i['id'] == $id) return $i['name'];
    }
}

echo GetTagName($tagArray, 46);

?>

So I guess it is a little simplified, but still not quite as simple as the JavaScript Array.filter() function.

I hope this helps!

Batman 310
add comment

Your Answer