PHP数组:通过索引获取值

时间:2017-05-30 16:00:11

标签: php arrays

我有这个PHP数组:

$statuses = array(
  'delivery-ongoing' => array("status" => "at-10", "traffic" => "FCL", "type" => "export"),
  'delivered' => array("status" => "at-13", "traffic" => "FCL", "type" => "export"),
  'delivery-ongoing' => array("status" => "00--00", "traffic" => "FCL", "type" => "import"),
  'return-to-ongoing' => array("status" => "to-04", "traffic" => "FCL", "type" => "import"),
  'delivered' => array("status" => "at-13", "traffic" => "FCL", "type" => "import")
);

我必须按键选择状态"正在交付"其中type =" import"

我可以使用数组结构,因为它是我班级中的常量。

我试过

$statuses['delivery-ongoing']['status']

如何获得type =" import"的正确状态?

我需要做一种循环还是有其他方法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以使用array_filter

$filtered = array_filter($statuses, function($value, $key) {
    return ($key == 'delivery-ongoing' && $value['type'] == 'import');
}, ARRAY_FILTER_USE_BOTH);

print_r($filtered);

此外,正如评论中所建议的那样,您可以重新命名您的密钥,也可以在状态之后附加ID。

Eq:

'delivery-ongoing-101' => array("status" => "at-10", "traffic" => "FCL", "type" => "export"),

答案 1 :(得分:1)

这个阵列有几个问题:

1-括号中的错误在此行过早关闭:

'return-to-ongoing' => array("status" => "to-04", "traffic" => "FCL"), "type" => "import",

2-如果在同一阵列上定义相同的键两次,则无法访问使用此键定义的第一个元素。如果使用调试器,您将看到阵列中只有3个元素可用,因为有多个元素共享同一个键,只保存最后一个。

但要获得您正在寻找的价值,您可以使用此循环:

foreach ($statuses as $key => $value) {

    if($key == 'delivery-ongoing' && $value['type'] == 'import'){

        $result = $value['status'];

        break;
    }
}

循环结束后,$ result的类型导入状态可用。

答案 2 :(得分:1)

您的$状态必须具有以下结构:

$statuses = array(
  'delivery-ongoing' => array(
    array("status" => "at-10", "traffic" => "FCL", "type" => "export"), 
    array("status" => "00--00", "traffic" => "FCL", "type" => "import")
  ),
  'delivered' => array(
    array("status" => "at-13", "traffic" => "FCL", "type" => "export"), 
    array("status" => "at-13", "traffic" => "FCL", "type" => "import")
    ),
  'return-to-ongoing' => array(array("status" => "to-04", "traffic" => "FCL", "type" => "import")),
);

现在,你可以做你想做的事情:

 function filter_by_value ($array, $index, $value){ 
    if(is_array($array) && count($array)>0)  
    { 
        foreach(array_keys($array) as $key){ 
            $temp[$key] = $array[$key][$index]; 

            if ($temp[$key] == $value){ 
                $newarray[$key] = $array[$key]; 
            } 
        } 
      } 
  return $newarray; 
} 

$imported = filter_by_value($statuses['delivery-ongoing'], 'type', 'import');

print_r($imported);