【问题标题】:Array with multiple "primary key" columns具有多个“主键”列的数组
【发布时间】:2026-01-25 20:00:01
【问题描述】:

我创建一个这样的数组:

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

谢谢!

【问题讨论】:

标签: php arrays search


【解决方案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'];
}

【讨论】:

    【解决方案2】:
    $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;
    

    【讨论】:

    • 但是当您建议这样填充时,“项目 1 存储 2”将覆盖“项目 1 存储 1”.. 不要?
    • 使用您的方法索引将是(0,1,2,3,4...),而在我的示例中,这些是由我们提供的,因此我们可以检查并做出决定,这取决于您和当您需要填充阵列时,您的系统流程。但这样你可以覆盖或防止重复推入数组