Find value from multidimensional array from given two values

82 views Asked by At

I have the following array.

Array
(
    [0] => Array
        (
            [product] => p1
            [item] => q1
            [date] => d1
            [status] => N
        )

    [1] => Array
        (
            [product] => p2
            [item] => q2
            [date] => d2
            [status] => Y
        )

    [2] => Array
        (
            [product] => p1
            [item] => q3
            [date] => d3
            [status] => N
        )
)

From this array, I want date from above with the given product and value.

For Example, I have product = p2 and item = q2 as a string. Now from this array, I want a date from this array which has product = p2 and item = q2.

So I need output from the above example is: d2

I tried array_column and array_search but can't find value from product and item both.

Please help me out with this in PHP.

2

There are 2 answers

0
Mikhail Prosalov On

You can iterate over your products and check required criteria with if statement.

foreach ($products as $product) {
    if ('p2' === $product['product'] && 'q2' === $product['item']) {
        var_dump($product['date']);
    }
}
0
jspit On

The conditions are as a string of type

$strCond = "product = p2 and item = q2";

given? This is converted into an array which can be processed better:

parse_str(str_replace(' and ','&',$strCond),$cond);
/*
$cond = array (
  'product_' => " p2",
  'item_' => " q2",
);
*/

array_filter() with a closure which cleverly uses array_intersect_assoc() delivers the result.

$result = array_filter($input,function($row) use($cond){
  return array_intersect_assoc($cond, $row) === $cond;
});

Result:

array (
  1 => 
  array (
    'product' => "p2",
    'item' => "q2",
    'date' => "d2",
    'status' => "Y",
  ),
)

As a rule, with such multidimensional arrays there are always several data records in the result. You can get the date of the first record like this:

$firstDate = reset($result)['date'];  //d2

Note: The algorithm was taken from PHP class tableArray.

One way of solving with this class:

$result = tableArray::create($input)
  ->filterEqual($cond)
  ->fetchRow()
;
/*
$result = array (
  'product' => "p2",
  'item' => "q2",
  'date' => "d2",
  'status' => "Y",
)
*/