in_array() 不适用于二维关联数组?

San*_*tri 0 php arrays multidimensional-array

我试图非常简单地使用 in_array() 来检查一个键是否在数组中,然后回显它的值。

$array = Array
( 
    [cart_item] => Array 
        ( 
            [0] => Array 
                ( 
                    [product_name] => White Sakura Necktie
                    [id] => 11
                    [product_auto_id] => 556729685
                    [quantity] => 2
                    [product_regular_price] => 95
                    [product_sale_price] => 95
                    [product_image] => 556729680Black_Sakura_Necktie.jpg 
                )
            [1] => Array 
                ( 
                    [product_name] => hhhad ba bhdbh
                    [id] => 10
                    [product_auto_id] => 951790801
                    [quantity] => 2
                    [product_regular_price] => 20
                    [product_sale_price] => 
                    [product_image] => 951790801hhhad_ba_bhdbh_.jpg 
                )
        ) 
)
Run Code Online (Sandbox Code Playgroud)

我有值 556729685 我想检查这个值是否存在?所以我为此使用 in_array() 函数。

in_array(556729685, array_keys($array));
in_array(556729685, array_values($array));
in_array(556729685, $array);
Run Code Online (Sandbox Code Playgroud)

以上三个我都用过,但结果总是显示 NULL 表示空白。

我真的很沮丧找到解决方案。我不明白发生了什么。

Gru*_*ton 7

您应该使用array_column()which 将输入数组中单列的值作为数组返回。

$product_auto_ids = array_column($array['cart_item'], 'product_auto_id');
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它将返回以下内容:

Array
(
    [0] => 556729685
    [1] => 951790801
)
Run Code Online (Sandbox Code Playgroud)

然后你可以in_array()像现在一样使用。

in_array(556729685, $product_auto_ids);
Run Code Online (Sandbox Code Playgroud)