You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将对象数组中size含round的元素移动到数组开头

实现方案

你不需要单独做unset再插入的操作,遍历一次数组拆分出圆形尺寸和普通尺寸两类,再合并数组即可,原有元素的属性和顺序都不会被破坏:

public function getDesignSize()
{
    $design =  $this->input->post('design', true);
    $quality =  $this->input->post('quality', true);
    $currentSizeData = $this->products_model->getAllPropDataForProductSize('sku_list', 
    array('size', 'url', 'color'), array('quality' => $quality, 'design' => $design, 'url is 
    NOT NULL' => NULL), array('size,color', 'asc'));

    // 拆分两类尺寸
    $roundSizes = [];
    $normalSizes = [];
    foreach ($currentSizeData as $item) {
        // PHP8+支持str_contains,低版本可以替换成preg_match或者strpos写法
        if (str_contains($item->size, 'round')) {
            $roundSizes[] = $item;
        } else {
            $normalSizes[] = $item;
        }
    }

    // 合并数组,圆形尺寸在前,普通尺寸在后
    $currentSizeArray = array_merge($roundSizes, $normalSizes);

    // 后续业务逻辑...
}

如果你的PHP版本低于8.0,把判断条件替换成下面任意一种写法即可:

// 写法1
if (preg_match("/round/", $item->size)) {
// 写法2
if (strpos($item->size, 'round') !== false) {

处理后的$currentSizeArray就是你需要的结构,所有带round的尺寸会按照原有顺序排在数组最前面,剩余普通尺寸保持原来的排序接在后面。

内容的提问来源于stack exchange,提问作者Alper Uluses

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 23:18:03