在具有多个相同键名的多维数组中搜索值

时间:2018-11-17 12:20:55

标签: php multidimensional-array

想象你有这个数组

Array(
[0] => Array
    (
        ['id'] => 12,
        ['filter'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 44444
                    )

            ),

        ['filtervalue'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 12345
                    )

            )

    ),
[1] => Array
    (
        ['id'] => 24,
        ['filter'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 44444
                    )

            ),

        ['filtervalue'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 12
                    )

            )

    ),
[2] => Array
    (
        ['id'] => 25,
        ['filter'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 55555
                    )

            ),

        ['filtervalue'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 123
                    )

            )

    ),
[3] => Array
    (
        ['id'] => 26,
        ['filter'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 55555
                    )

            ),

        ['filtervalue'] => Array
            (
                ['resource'] => Array
                    (
                        ['id'] => 12
                    )

            )

    )
);

我想知道这两个值是否存在:

如果filter-> resource-> id == 55555并且if filtervalue-> resource-> id == 12 所以在这个数组中它们存在于[3]中,所以是真的

如果我要搜索 如果filter-> resource-> id == 44444,并且如果filtervalue-> resource-> id == 123

那么,尽管[0]中存在4444,[2]中存在[1]和123,但仍会给出错误的消息

我很想这个问题

3 个答案:

答案 0 :(得分:0)

您可以使用foreach循环来实现此功能,并检查所需条件并获取其索引:

$index = '';
foreach ($records as $key => $record) {
    if (($record['filter']['resource']['id'] == 55555) && ($record['filtervalue']['resource']['id'] == 12)) {
        $index = $key;
        break;
    }
}

答案 1 :(得分:0)

$found = false;
foreach ($yourArray as $item) {
    if ($item['filter']['resource']['id'] == $someVal && $item['filtervalue']['resource']['id'] == $anotherVal) {
        $found = true;
        break;
    }
}
var_dump($found);

答案 2 :(得分:0)

$filters = []; // Your array
$r = 44444;
$v = 123;
foreach( $filters as $f ){
    if( $r === (int) $f ['filter']['resource']['id'] ){
      $r = true;
    }
    if( $v === (int) $f ['filtervalue']['resource']['id'] ){
      $v = true;
    }
    if( TRUE === $r && TRUE === $v ){
      echo "FOUND!!!\n";
      break;
    }
}

i am probobly overthinking the problem-绝对!