在数组中查找数据

时间:2016-01-06 16:37:45

标签: php arrays

我有这个数组数据:

Array
(
    [0] => Array
        (
            [product_sequence] => 1
            [quantity] => 1
            [attributes] => Array
                (
                )

        )

    [1] => Array
        (
            [product_sequence] => 1
            [quantity] => 1
            [attributes] => Array
                (
                    [Colour] => Black 
                )

        )

)

通过product_sequence

搜索此数组的最佳方法是什么

我厌倦了:

array_search('1', $_SESSION["cart"])

但这根本不会返回任何数据

2 个答案:

答案 0 :(得分:1)

请尝试使用此

要查找符合搜索条件的值,您可以使用<div id="input"></div> <div id="output"></div>功能:

表示价值:

array_filter

表示密钥:

$searchword = '1';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); })

答案 1 :(得分:0)

您可以使用foreach,也可以使用array_filter。一个简化的例子:

<?php

$products = [
    [
        'product_sequence' => 1,
    ],
    [
        'product_sequence' => 1,
    ],
    [
        'product_sequence' => 2,
    ]
];


$productSequence = 1;

$filteredProducts = array_filter($products, function($product) use ($productSequence) {
    // only return elements that test `true`
    return $product['product_sequence'] === $productSequence;
});

print_r($filteredProducts);

收率:

Array
(
    [0] => Array
        (
            [product_sequence] => 1
        )

    [1] => Array
        (
            [product_sequence] => 1
        )

)

更多阅读:

希望这会有所帮助:)