如何在php中获取特定的数组值?

时间:2011-11-19 06:14:09

标签: php

我有以下$qtips_messages数组,

Array
(
    [0] => Array
        (
            [id] => 1
            [tips_title] => email_tips 
            [tips_message] => ex:xxxxx@xyz.com
            [tips_key] => key_email
        )

    [1] => Array
        (
            [id] => 2
            [tips_title] => website_tips 
            [tips_message] => ex:http://www.yahoo.co.in
            [tips_key] => key_website
        )

    [2] => Array
        (
            [id] => 3
            [tips_title] => zipcode_tips
            [tips_message] => ex:60612
            [tips_key] => key_zipcode
        )

    [3] => Array
        (
            [id] => 4
            [tips_title] => phone_tips 
            [tips_message] => ex:1234567890
            [tips_key] => key_phone
        )
)

例如,我想获取tip_title'mail_tips'的提示消息 我尝试过以下代码,

foreach($qtips_messages as $qtipsArray){
    foreach($qtipsArray as $qkey=>$qvalue){
        if($qtipsArray['tips_title'] == 'email_tips'){
            $emailtipsMessage = $qtipsArray['tips_message'];
        }
    }
}

当我运行上面的代码时,我没有得到任何价值 这段代码有什么问题?

3 个答案:

答案 0 :(得分:2)

你只需要一个循环:

$message = null;
foreach ($array as $tips) {
    if ($tips['tips_title'] == 'email_tips') {
        $message = $tips['tips_message'];
        break;
    }
}

我可能会选择这样的东西:

$message = current(array_filter($array, function ($tip) { return $tip['tips_title'] == 'email_tips'; }));
echo $message['tips_message'];

答案 1 :(得分:1)

$array  = array();
foreach($result AS $k =>$val)
   $array[$val['tips_key']]    = $val['tips_message'];
return $array;

现在,数组$数组具有基于键的q-tips的所有值...

希望这会对你有帮助......

答案 2 :(得分:0)

尝试这种方式。

$array  = array();  
foreach($qtips_messages AS $k =>$val):  
if($val['tips_title']=='email_tips')  
{  
  $array[$val['tips_key']] = $val['tips_message'];  
  print_r($array);  
  break;  
}  
endforeach;