0

I have this array data:

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

        )

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

        )

)

whats the best way to search this array by the product_sequence

i tired using:

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

but this doesnt return any data at all

5
  • The best way is to use foreach Commented Jan 6, 2016 at 16:40
  • would that be the quickest way too? Commented Jan 6, 2016 at 16:40
  • What do you mean by "search"? You just want the arrays that have product_sequence = 1? Commented Jan 6, 2016 at 16:41
  • WIth this array structure foreach is the only way Commented Jan 6, 2016 at 16:41
  • array_column($_SESSION["cart"], "product_sequence") for php >= 5.5 Commented Jan 6, 2016 at 16:46

2 Answers 2

1

Please try with this

To find values that match your search criteria, you can use array_filter function:

for value:

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

for key:

$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
        $matches[$k] = $v;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use foreach or you can use array_filter. A simplified example:

<?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);

Yields:

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

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

)

More reading:

Hope this helps :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.