【问题标题】:If there are several records with the same value in array column - take one record with minimum value of other column如果数组列中有多条具有相同值的记录 - 取一条具有另一列最小值的记录
【发布时间】:2019-07-01 13:40:56
【问题描述】:

我的多维数组长这样:

Array3: [
    0 => array:2 [
            model_id => 1
            price => 2000
         ]      
    1 => array:2 [
            model_id => 2
            price => 3000
         ]
    2 => array:2 [
            model_id => 1
            price => 1500
         ]
   ]

现在我需要检查 model_id 的值是否多次出现,如果是这样,我需要在价格值较低的地方取这个。在这个例子中,我有两次 model_id = 1,所以我应该拿第二个,因为价格最低。

我该怎么做?我试过这种方法:

how can I get the duplicate multidimensional array in php

PHP: Check for duplicate values in a multidimensional array

Finding Duplicate Values in Multi-dimensional Array

但我仍然无法处理这个问题。结果数组应如下所示:

Array2: [
    0 => array:2 [
            model_id => 2
            price => 3000
         ]
    1 => array:2 [
            model_id => 1
            price => 1500
         ]
   ]

【问题讨论】:

  • @Cid 我已经编辑了我的帖子
  • 你放弃了吗???
  • @AbraCadaver 不,不,我测试了建议的解决方案,但我还没有实施任何具体的解决方案。我很惭愧地承认,但我担心我正在寻找的解决方案不会是我的最佳解决方案。我将尝试通过建议的数组过滤来解决问题,但我认为我需要不同的方法来解决它

标签: php arrays laravel


【解决方案1】:

简单的foreach 应该这样做:

foreach($arr as $e) {
    if (isset($res[$e["model_id"]]))
        $res[$e["model_id"]]["price"] = min($res[$e["model_id"]]["price"], $e["price"]);
    else $res[$e["model_id"]] = $e;
}

现场示例:3v4l

【讨论】:

    【解决方案2】:

    您可以利用关联数组键来强制唯一性并比较价格:

    <?php
    // Our data
    $array = [
        [ 'model_id' => 1, 'price' => 2000 ],
        [ 'model_id' => 2, 'price' => 3000 ],
        [ 'model_id' => 1, 'price' => 1500 ]
    ];
    
    // Store the final result
    $result = [];
    
    // Loop the data
    foreach( $array as $v )
    {
        // If this model_id has not been encountered or if the price is lower than what's stored then make it the new price
        if( !isset( $output[ $v[ 'model_id' ] ] ) || $v[ 'price' ] < $output[ $v[ 'model_id' ] ][ 'price' ] )
        {
            $output[ $v[ 'model_id' ] ] = $v;
        }
    }
    
    // Get rid of the unique keys
    $output = array_values( $output );
    
    print_r( $output );
    

    输出:

    Array
    (
        [0] => Array
            (
                [model_id] => 1
                [price] => 1500
            )
    
        [1] => Array
            (
                [model_id] => 2
                [price] => 3000
            )
    
    )
    

    【讨论】:

      【解决方案3】:

      您可以按price 降序排序,然后在model_id 上提取和索引,这样最后一个(每个model_id 索引中的最低price)将覆盖其他:

      array_multisort(array_column($array, 'price'), SORT_DESC, $array);
      $result = array_column($array, null, 'model_id');
      

      【讨论】:

        【解决方案4】:

        您可以将它们分组为model_id 而不是使用min 函数

        $groupByModelId = [];
        foreach($a as $v){
          $groupByModelId[$v['model_id']][] = $v['price'];
        }
        $searchModelId = 1;
        echo min($groupByModelId[$searchModelId]);
        

        Working DEMO

        【讨论】:

          【解决方案5】:

          这里还有一种方法,

          function array_column1($input, $column_key = null, $index_key = null)
          {
              $result = [];
              $i      = 0;
              foreach ($input as $v) {
                  $k            = $index_key === null || !isset($v[$index_key]) ? $i++ : $v[$index_key];
                  // fetching all the values for model id
                  $result[$k][] = $column_key === null ? $v : (isset($v[$column_key]) ? $v[$column_key] : null);
              }
              // fetching minimum for every model_id
              $result = array_map("min", $result);
              return $result;
          }
          $temp = array_column1($arr, 'price', 'model_id');
          

          Demo.

          我从官方phpdoc使用了这个函数。

          【讨论】:

            【解决方案6】:

            您可以使用 usort 数组函数来获取第一个最小值记录,然后使用 temp 数组并运行 foreach 函数来删除重复记录。

            下面的代码对我来说很好。

            <?php
            
            
            $arr = array(
                    [   
                        'model_id' => 1,
                        'price' => 2000
                    ],
                    [
                        'model_id' => 2,
                        'price' => 3000
                    ],
                    [
                        'model_id' => 1,
                        'price' => 1500
                    ]
                );
            
                usort($arr, function ($a, $b) {
                    return $a['price'] - $b['price'];
                });
            
                $input = $arr;
                $temp  = array();
                $keys  = array();
            
                foreach ( $input as $key => $data ) {
                    unset($data['price']);
                    if ( !in_array($data, $temp) ) {
                        $temp[]     = $data;
                        $keys[$key] = true;
                    }
                }
            
                $output = array_intersect_key($input, $keys);
            
                print_r($output);
            

            【讨论】:

              猜你喜欢
              • 2020-03-05
              • 2022-01-11
              • 2015-02-15
              • 2020-05-20
              • 1970-01-01
              • 1970-01-01
              • 2021-09-23
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多