0

I have an array like this:

$array=[
    0 => [col_a => 1, col_b => 2, col_c =>3],
    1 => [col_a => 2, col_b => 3, col_c =>4]
];

Is there a way to do something like:

$result=query_array($array,"SELECT col_c FROM ARRAY WHERE col_a=2 AND col_b=3");
print_r($result);
// array (col_c => 4)

EDIT:

where query_array is a function that executes SQL to an array.

I know I can loop between the elements and test every "row". I was wondering if there is a build-in function that does that like that fictional query_array function.

2
  • 2
    nope, it's not query_array, you could only filter it based on its keys or value. reference if you're interested.. Commented Jan 3, 2017 at 10:29
  • well, if you really need it, you could use array_filter(..) and make the callbacks to emulate your where clause.. Commented Jan 3, 2017 at 10:41

2 Answers 2

1
$arrays = [
   ['col_a' => 1, 'col_b' => 2, 'col_c' => 3],
   ['col_a' => 2, 'col_b' => 3, 'col_c' => 4]
];


foreach ($arrays as $array) {
   $res = array_filter($array, function($v, $k) {
      return ($k == 'col_a' && $v == 2) || ($k == 'col_b' && $v == 3);
   }, ARRAY_FILTER_USE_BOTH);

   if (count($res) == 2) {
      print_r([
          'col_c' => $array['col_c']
      ]);
   }
}

Try something like this

Sign up to request clarification or add additional context in comments.

Comments

1
 $array=[
    0 => ['col_a' => 1, 'col_b' => 2, 'col_c' =>3],
    1 => ['col_a' => 2, 'col_b' => 3, 'col_c' =>4]
];


$val1 =2;
$val2 = 3;
$isArray = array_values(array_filter($array, function ($data) use ($val1,$val2) {
    return ($data['col_a'] == $val1 &&  $data['col_b'] == $val2);
}));

1 Comment

additional note, this will not preserve original array's key.. while array_filter does.

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.