给定一定的已知值,在PHP数组中访问相应的值

时间:2013-02-22 08:50:03

标签: php arrays

假设我有一个如下所示的数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Group1
            [description] => This is the group1.
        )

    [1] => Array
        (
            [id] => 2
            [title] => Group2
            [description] => This is group2.
        )

)

假设标题被称为“Group2”。如果它不知道它,密钥,id等只有标题,我怎么能够确定使用PHP它的等效描述(即“这是group2”)?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

试试这个:

$title = "Group2";

foreach($your_array as $val){
   if($val['title'] == $title){
      echo $val['description'];
      break; //cut back on unnecessary looping
   }
}

答案 1 :(得分:0)

你必须遍历主阵列并扫描它以获得该标题。

假设您的主阵列名为$groups

$title = 'Group2';
foreach($groups as $key => $group){
  if ($group['title'] == $title){
    $groupDescription = $group['description'];
    // if you need to reference this group again, save it's key.
    $groupKey = $key;
  }
}

您可以在找到要查找的组后插入break命令来终止循环,以便在找到您要查找的阵列后不会继续扫描阵列。

答案 2 :(得分:0)

试试这个

foreach($myarray as $val){
  if($val['title'] == "Group2"){
     echo 'This is description '.$val['description'];
   }
}