Comparing Multi and single dimensional arrays in php -


i new php playing array. want following things array of different dimensional

the following multidimensional array

$a = array( array(     'productsid' => 90,     'couponid' => 50 ), array(     'productsid' => 80,     'couponid' => 95 ),   array(     'productsid' => 80,     'couponid' => 95 )); 

the following single dimensional array:

$b = array(80,90,95); 

i want compare productsid index of array single dimensional array , wants fetch data equal it.

i have tried following loop print gives values of productsid want full array. comparing productid second array.

for ($i = 0; $i < 3; $i++) { foreach ($a[$i] $key => $value) {     foreach ($b $c) {         if ($value == $c) {             echo $value .'<br>';          }     } } } 

looks you're looking in_array():

$result = array(); foreach($a $item)     if(in_array($item['productsid'], $b))         $result []= $item; 

or, in more concise (but less readable imo) way:

$result = array_filter($a, function($item) use($b) {     return in_array($item['productsid'], $b); }); 

for test data it's doesn't matter much, if arrays big and/or loop going run many times, can achieve better performance converting lookup array hash table , using o(1) key lookup instead of linear array search:

$bs = array_flip($b); $result = array_filter($a, function($item) use($bs) {     return isset($bs[$item['productsid']]); }); 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -