具有多个“主键”列的数组

时间:2015-08-20 03:40:09

标签: php arrays search

我创建了一个这样的数组:

$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) );

我需要搜索我是否在某个存储空间中有一些项目.. 例如在sql查询中,我喜欢“... where item = 1 and storage = 2”

如何在数组中搜索这种方式,以获得“qtd”值?

谢谢!

2 个答案:

答案 0 :(得分: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 **** 获得$table数组中最高的最大索引

$current_primary_key =   max(array_keys($table));
$next_primary_key = $current_primary_key + 1;

答案 1 :(得分:0)

使用alamnaryab的建议,我改成这样的东西,对我有用:

NSUserdefaults