【问题标题】:PHP array - `array_splice` issuePHP 数组 - `array_splice` 问题
【发布时间】:2016-06-15 20:37:25
【问题描述】:

我正在使用 PHP 数组来存储产品 ID 的逗号分隔值,然后依次使用它们显示为最近看到的产品。

实现如下:

$product_data = array();
$array_ids_a_display = array();   
$check_status = array();
$array_check= array();
$_COOKIE['Pr'] = [1,2,3,4,5,6,7,8]

那我取存储字符串的最后一点

$array_check = explode(',',substr($_COOKIE['IdProduto'],0,-1));

现在,我检查产品是否已启用,然后将它们存储到另一个数组中

foreach($array_check as $id_a_checar){
    $check_status = $this->model->getProduct($id_a_checar);
    if($check_status['status']){ // If status is 1
        $array_ids_a_display[$contprods++] = $id_a_checar;
    }
}

if($s['limit']>count($array_ids_a_display)){ 
    //If the number of valid products < number of products of module
    $s['limit'] = count($array_ids_a_display);  
      //will show,then reconfigures the number of products that will show
  }   
}

其中$s['limit'] 来自后端,让我们说6 来限制产品数量。

现在,我将反转数组以首先获取最新访问的产品,如 as

$last_ended = array_reverse($array_ids_a_display);
array_splice($last_ended,0,(int)$s['limit']);
foreach ($last_ended as $result) {
    $product_data[$result] = $this->product->getProduct($result);
}     

现在问题来了,因为我只在 $product_data 数组中获得 3 个产品,但应该获得 6 个产品。 p>

我希望array_splice 存在问题,因为如果我将评论 array_splice,那么我将在 cookie 中获取所有商店产品。 Mysql 查询运行良好。

请告知如何从数组中获取最新的 6 个值

【问题讨论】:

  • 如果我是你,我会做的第一件事就是进行回声调试,看看你的数据在哪里丢失
  • 我写过我的数据有array_splice的问题
  • 直到数组反转我得到所有 8 个 ID
  • 您的数据是您需要展示的。没有人知道你的数据是什么。

标签: php mysql arrays


【解决方案1】:

你在这里:

$last_ended = array(1, 2, 3, 4, 5, 6, 7, 8);
$last_ended = array_reverse($last_ended);
//here is what you missed:
$last_ended = array_splice($last_ended, 0, 6);

print_r($last_ended);
//returns Array ( [0] => 8 [1] => 7 [2] => 6 [3] => 5 [4] => 4 [5] => 3 )

您需要将您的 $last_ended 变量分配array_splice 结果中。

【讨论】:

    【解决方案2】:
    <?php
    // Get the last 6 entries of an array...
    $arr = array(
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8
    );
    
    $entries = array_splice($arr, -6);
    // returns [3, 4, 5, 6, 7, 8]
    

    }

    【讨论】:

      【解决方案3】:
      $maxResultLength = 6;
      $someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
      $startIndex = (count($someArray) >= $maxResultLength) ? count($someArray) - $maxResultLength : 0;
      $lastSixElements = array_slice($someArray, $startIndex, $maxResultLength);
      

      $maxResultLength = 6;
      $someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
      $lastSixElements = array_splice($someArray, -6);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-30
        • 2012-07-20
        • 2010-12-19
        • 2015-08-11
        • 2011-02-17
        • 2011-10-17
        • 1970-01-01
        相关资源
        最近更新 更多