簡體   English   中英

具有多個“主鍵”列的數組

[英]Array with multiple “primary key” columns

我創建一個像這樣的數組:

$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”值?

謝謝!

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

編輯****以在$table數組中獲得最高的最大索引

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

借助alamnaryab的建議,我更改為類似這樣的內容:

$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'];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM