获取关联数组的元素

时间:2018-08-13 21:49:36

标签: php arrays

有时候我有一个名为labels = { 'inputPhone': 'Mobile phone', 'inputCity': 'City' }; placeholders = { 'inputPhone': '987 333 987', 'inputCity': 'Las Vegas' }; required = { 'inputCity': true }; 的变量,这个变量从Excel中的数据返回头盔或手套,并且我有这个关联数组

$data

在数据变量等于手套的情况下,我想对照数组元素检查$productCateegories = array ( "Helmets" => 30, "Gloves" => 20, "Helmet"=> 10); 变量,然后将另一个名为$data的变量设置为20。

3 个答案:

答案 0 :(得分:0)

$productCateegories = array ( "Helmets" => 30, "Gloves" => 20, "Helmet"=> 10);
$data = 30;

与访问数组元素中使用的索引不同,使用键访问关联数组元素。如果您比较关联数组和$data变量,可以尝试下面的代码。

$data2 = null;
//when checking if it's equal to "Gloves"
if($data == $productCateegories["Gloves"]){
    $data2 = $productCateegories["Gloves"];
    //do other things
}
//when checking if it's equal to "Helmets"
else if($data == $productCateegories["Helmets"]){
    $data2 = $productCateegories["Helmets"]; 
    //do other things
}
//when checking if it's equal to "Helmet"
else if($data == $productCateegories["Helmet"]){
    $data2 = $productCateegories["Helmet"]; 
    //do other things
}

答案 1 :(得分:0)

PHP有一个称为变量变量的概念。

可以允许您做什么:

${$data}Count=$productCategories[$data];

然后您可以将头盔计数和手套计数获取为:

echo $helmetCount;

echo $gloveCount;

答案 2 :(得分:0)

类似以下的方法应该起作用。

if (in_array($data, array_keys($productCateegories)) {
    // Do something if in array.
}

否则,您也可以像这样进行检查,这将检查它是否已设置,然后设置该值。

if (isset(productCateegories[$data])) {
    $data2 = $productCateegories[$data];  // 20
}