PHP -根据多维数组检查值


PHP - Check for a value against a multidimensional array

我有一个多维数组,像这样:

$pover = 
    Array
    (
        [0] => Array
            (
                [item_name] => "iPhone 5s Repair"
                [service_name] => "Touchscreen & LCD repair"
                [service_price] => 49.99
            )
        [1] => Array
            (
                [item_name] => "iPhone 5C Repair"
                [service_name] => "Power button replacement"
                [service_price] => 29.99
            )
    )

现在我有两个值:

$item = 'iPhone 5s Repair';
$service = 'Touchscreen & LCD repair';

现在,我首先要检查项目$item是否在数组中,然后获取service_price并将其显示在页面上。我尝试使用array_search:

搜索iPhone 5s Repair数组
$key = array_search($ititle, $pover);
echo $key;

但是它没有输出任何东西。有人能给我指路吗?

array_search()是否工作的多维数组我担心。你能做的最好的事情就是自己浏览数组。

foreach ($pover as $key => $value) {
  if ($value["item_name"] == "YOUR_TITLE") {
    /* Item found */
  }
}

尝试循环搜索您的项目。

// The value of what you're searching for 
$title = 'iPhone 5s Repair';
for($i=0;$i<count($pover);$i++) {
    $item = $pover[$i]['item_name'];
    // Foreach item in the array, see if it's one of the ones that you need
    if($title == $item) {
       $price = $pover[$i]['service_price'];
       $service = $pover[$i]['service_name'];
       echo "Found at ".$i."<br />";
       echo "The price for the ".$item." is ".$price."<br />";
    }
}

另一个有趣的选择是使用PHP 5.5中最近添加的array_column()函数(对于旧版本的PHP有一个用户层实现,地址是https://github.com/ramsey/array_column):

<?php
function getPrice($item, $array) {
    $array  = array_values($array);
    $column = array_column($array, 'item_name');
    if (in_array($item, $column)) {
        return $array[array_search($item, $column)]['service_price'];
    }
    return false;
}
print getPrice($item, $pover);

你必须自己搜索数组,没有其他方法

<?php
foreach ($pover as $delta => $record) {
  if ($record["item_name"] === $ititle) {
    $key = $delta;
    break;
  }
}