PHP - 按变量搜索多维关联数组

时间:2013-02-18 19:42:46

标签: php

我有这个多维关联数组:

$store = array(
array("id" => 13,"store_id" => 4,"name" => "trumpet","type" => "trumpet567"),
array("id" => 15,"store_id" => 3,"name" => "piano","type" => "piano689"),
array("id" => 33,"store_id" => 1,"name" => "flute","type" => "flute267"),
array("id" => 77,"store_id" => 3,"name" => "violin","type" => "violin324"),
array("id" => 78,"store_id" => 2,"name" => "guitar","type" => "guitar364"),
array("id" => 91,"store_id" => 3,"name" => "accordion","type" => "accordion763"));

和变量:

$instrument="guitar";

我需要获得$ instrument的store_id。我尝试了很多东西,但我没有解决方案:(

1 个答案:

答案 0 :(得分:4)

$instrument = 'guitar';
$storeId = null;

foreach ($store as $row) {
    if ($row['name'] == $instrument) {
        $storeId = $row['store_id'];
        break;
    }
}

echo $storeId; // Will echo 2.