按名称在多维数组中查找项,并返回同一数组中的值

时间:2011-04-27 16:04:20

标签: php arrays multidimensional-array

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

array(3) {
    [1]=> array(7) {
        ["label"]=> string(43) "I would like to receive PCN for ETXexpress:"
        ["name"]=> string(48) "ilts_I_would_like_to_receive_PCN_for_ETXexpress:"
        ["type"]=> string(8) "checkbox"
        ["wert"]=> string(2) "on"
        ["html_after"]=> string(0) ""
        ["label_after"]=> string(0) ""
        ["size"]=> string(0) ""
    }
    [2]=> array(7) {
        ["label"]=> string(50) "I would like to recieve PCNs for microETXexpress®"
        ["name"]=> string(55) "ilts_I_would_like_to_recieve_PCNs_for_microETXexpress®"
        ["type"]=> string(8) "checkbox"
        ["wert"]=> NULL
        ["html_after"]=> string(0) ""
        ["label_after"]=> string(0) ""
        ["size"]=> string(0) ""
    }
    [3]=> array(7) {
        ["label"]=> string(38) "I would like to recieve PCNs for ETX®"
        ["name"]=> string(43) "ilts_I_would_like_to_recieve_PCNs_for_ETX®"
        ["type"]=> string(8) "checkbox"
        ["wert"]=> NULL
        ["html_after"]=> string(0) ""
        ["label_after"]=> string(0) ""
        ["size"]=> string(0) ""
    }
}

如何通过名称获取其中的数组? 假设:从包含ilts_I_would_like_to_recieve_PCNs_for_microETXexpress®值的数组wert

对我来说很重要,不要用数组中的数字指出它。

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分:2)

$data = array( /* your data */ );
$name = "ilts_I_would_like_to_recieve_PCNs_for_microETXexpress®"; // name you are looking for
$result = array();

foreach ( $data as $key => $value ) {
    if ( $value['name'] == $name ) {
        $result = $value;
        break;
    }
}

答案 1 :(得分:0)

测试此代码,我认为这应该可行。

<?PHP
$array = array( /* YOUR DATA */ );

$out = array();

foreach( $array as $a )
{
    if( $a['name'] == 'ilts_I_would_like_to_recieve_PCNs_for_microETXexpress®' )
    {
        $out = $a;
        break;
    }
}

print_r( $out );
?>

答案 2 :(得分:0)

为什么你不用记录名替换数组键(0,1,2 ......),因为它们是唯一的。像这样,您无需搜索即可访问您的记录:

if (array_key_exists($name, $yourArray))
{
    // your code ..
}