简体   繁体   English

如何在数组中搜索以查找包含特定值的所有子数组

[英]how to search in array to find all sub arrays that contain a certain value

i have a array placed in the variable $class that is constituted of sub arrays containing 2 student id's each, i am trying to find all the sub arrays that contain a certain id for example 11 i want to keep all arrays containing this id in a variable. 我在变量$class中放置了一个数组,该数组由每个包含2个学生ID的子数组组成,我试图查找包含某个id所有子数组,例如11我想将包含该ID的所有数组保留在一个数组中变量。

array example 数组示例

Array
(
    [0] => Array
        (
            [s1] => 6
            [s2] => 37
        )

    [1] => Array
        (
            [s1] => 8
            [s2] => 11
        )

    [2] => Array
        (
            [s1] => 11
            [s2] => 48
        )

)

code

foreach ($class as $key => $value) {
    if(!in_array($id, $class)){
        unset($class[$key]);
    }
}

You are close. 你近了 If you loop and reference the correct variable with the in_array(), it would work as you hopefully need. 如果循环并使用in_array()引用正确的变量,它将按您希望的那样工作。 Then assign the matching array into a new array var to use later (so you are not altering your original array!): 然后将匹配的数组分配到新的数组var中以供以后使用(这样就不会更改原始数组!):

$id = 11;
$matched = array();
foreach ($class as $i => $students) {
    if ( in_array($id, $students) ) {
        $matched[] = $class[$i];
    }
}

print_r($matched);

Would result in: 将导致:

Array (
     [0] => Array
         (
             [s1] => 8
             [s2] => 11
         )
     [1] => Array
         (
             [s1] => 11
             [s2] => 48
         )
     )

Associative array http://php.net/manual/es/function.array-search.php 关联数组http://php.net/manual/es/function.array-search.php

$class = array(array("s1"=>6, "s2"=>37),array("s1"=>8,"s2"=>11),array("s1"=>11, "s2"=>48));
$id = 11;
foreach ($class as $key => $value) {
    if(!array_search($id, $value)){
        unset($class[$key]);
    }
}

Sorry, you can follow this answers using array_search for multi dimensional array 抱歉,您可以使用array_search多维数组来遵循此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM