从PHP数组中获取特定元素?

时间:2013-11-26 14:04:07

标签: php arrays

我的PHP代码中有一个数组,如下所示:

Array
(
[1] => Array
    (
        [subject_id] => 1
        [subject] => Math
        [default_selection] => 1
    )

[2] => Array
    (
        [subject_id] => 2
        [subject] => Physics
        [default_selection] => 0
    )

[3] => Array
    (
        [subject_id] => 3
        [subject] => Chemistry
        [default_selection] => 0
    )

[4] => Array
    (
        [subject_id] => 4
        [subject] => Biology
        [default_selection] => 0
    )

[5] => Array
    (
        [subject_id] => 5
        [subject] => Statistics
        [default_selection] => 0
    )

)

我想获得[subject]的值[subject_id] = 2.在PHP中是否有任何直接/快捷方式,或者我需要运行foreach循环?

4 个答案:

答案 0 :(得分:2)

如果您只需对同一数据执行此操作一次,只需运行foreach循环:

<?php
    $foundArray = null;

    foreach ($array as $subArray) {
        if ($subArray['subject_id'] == 2) {
            $foundArray = $subArray;
            break;
        }
    }

    var_dump($foundArray);
?>

如果您需要使用相同的数据(在同一请求中)检查subject_id很多,您可以将您的密钥与subject_id相关联,并以这种方式引用它:

<?php
    $assoc = array();

    foreach ($array as $subArray) {
        $assoc[$subArray['subject_id']] = $subArray;
    }

    var_dump($assoc[2]);
    var_dump($assoc[3]);
    var_dump($assoc[4]);
?>

答案 1 :(得分:1)

您可以使用array_map

使用此功能:

function getSubject($subject) {
   if  ($subject['subject_id'] == 2) return $subject; 
}

用法:

$subjects = array_map('getSubject', $array);
var_dump($subjects);

参考:Get specific key value pair from multidimensional array

答案 2 :(得分:1)

PHP 5.5中的新功能是array_column()功能,它可能会实现您所要求的功能(即不使用foreach()进行搜索):

$searchForSubjectID = 2;
$index = array_search($searchForSubjectID, array_column($data, 'subject_id'));
$subject = $data[$index]['subject'];

print $subject;  //prints 'Physics'

如果你还没有使用PHP 5.5,那就是a compatibility library for this function

答案 3 :(得分:0)

您可以使用array_filter选择正确的元素:

<?php
    function getSecondSubject( $element ){
        return $element["subject_id"] == 2;
    }

    $only_subject_two = array_filter( $all_subjects, "getSecondSubject" );

    $subject = $only_subject_two["subject"];
?>

如果需要,可以使用一些技巧(如变量)来使subject_id找到变量。