1

I create an array like this:

$table = Array();
array_push($table, Array('item' => 1, 'storage' = 1, 'qtd' = 0) );
array_push($table, Array('item' => 1, 'storage' = 2, 'qtd' = 4) );
array_push($table, Array('item' => 2, 'storage' = 1, 'qtd' = 78) );
array_push($table, Array('item' => 3, 'storage' = 2, 'qtd' = 10) );

I need to search if i have some item in some storage.. For example in a sql query i do like "... where item = 1 and storage = 2"

How can i search that way in the array, to get the "qtd" value?

Thanks!

  • 1
    i think your asking how to search a multidimensional array ? –  Aug 20 '15 at 03:43
  • easiest way would be to use [array_filter](http://php.net/manual/en/function.array-filter.php) with a callback function – Orangepill Aug 20 '15 at 03:44
  • 1
    http://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php?rq=1 ? –  Aug 20 '15 at 03:46

2 Answers2

0
$table = Array();

//populate $table array this way
$table[1]=array('item' => 1, 'storage' = 1, 'qtd' = 0);
$table[1]=array('item' => 1, 'storage' = 2, 'qtd' = 4);
$table[2]=array('item' => 2, 'storage' = 1, 'qtd' = 78);
$table[3]=array('item' => 3, 'storage' = 2, 'qtd' = 10);

//to prevent over-writting use in_array() function
if(!in_array(1 /*item*/ ,array_keys($table))){
    $table[1]=array('item' => 1, 'storage' = 1, 'qtd' = 0);
}

//the following will not be inserted as we have already a value at index=1
if(!in_array(1,array_keys($table)),){
    $table[1]=array('item' => 1, 'storage' = 2, 'qtd' = 4);
}     

EDITED**** to get highest max index in $table array

$current_primary_key =   max(array_keys($table));
$next_primary_key = $current_primary_key + 1;
alamnaryab
  • 1,480
  • 3
  • 19
  • 31
  • But when you sugest populated like this, the "item 1 storage 2" will over-writting the "item 1 storage 1".. Dont? – Netto Passaro Aug 20 '15 at 04:07
  • using your method indexes will be(0,1,2,3,4...) while in my example these are provided by us so we can check and make decision, it is upto you and your system flow when you need to populate the array. but this way you can overwrite or prevent duplicate pushing in array – alamnaryab Aug 20 '15 at 04:12
0

Using the suggestion of alamnaryab, i change to something like this, that works for me:

$table = Array();

$table[1][1]=array('qtd' => 0);
$table[1][2]=array('qtd' => 4);
$table[2][1]=array('qtd' => 78);
$table[3][2]=array('qtd' => 10);

if (!isset($table[1][2]))
{
    echo "Dosent Exists";
}
else
{
    echo "exists. qtd: " . $table[1][2]['qtd'];
}