0

How can I search a value in a multi dimensional array.

I would like to receive all keys looking for a specific date Ex(2012-07-25) in [created]

and receive array[0][0] and array[0][1]

Array
(
[0] => Array
    (
        [0] => Array
            (
                [id_store] => 3
                [id_product] => 11
                [monitored] => 0
                [created] => 2012-07-25
            )

        [1] => Array
            (
                [id_store] => 3
                [id_product] => 12
                [monitored] => 0
                [created] => 2012-07-25
            )

        [2] => Array
            (
                [id_store] => 4
                [id_product] => 11
                [monitored] => 0
                [created] => 2012-07-26
            )
    )

)
2
  • the user notes for array_search() have several examples: nz.php.net/manual/en/function.array-search.php Commented Jul 26, 2012 at 20:55
  • Is this a sufficiently challenging minimal reproducible example? Does your first level actually only contain a single item? nickb's answer is counting on that fact. Commented Nov 20, 2024 at 7:38

2 Answers 2

2

Something like this should work with array_filter():

$target = '2012-07-25';
$matches = array_filter( $array[0], function( $el) use( $target) {
    return $el['created'] == $target;
);
Sign up to request clarification or add additional context in comments.

Comments

0

Haven't tested this, but it should work:

$results = search_date($my_array, $my_date);

`

function search_date($array, $date, &$result=array())
{
    foreach($array as $key=>$value)
    {
        if($key == 'created' && $value == $date)
        {
            $result[]=$array;
            continue;
        }
        if(is_array($item))
        {
            search_date($item, $date, $result);
        }
    }
    return $result;
}

Personally, I would ditch your data format altogether and use an object model more suited for the task.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.