【问题标题】:Php, I need delete spesific text in array and later i need prepend itPhp,我需要删除数组中的特定文本,然后我需要添加它
【发布时间】:2021-11-30 20:06:16
【问题描述】:

如果索引内的大小包含“圆形”,我需要删除该索引并将其添加到数组中。因为圆形尺寸应该是第一位的。我尝试了 foreach 循环和 array_search 数据,后来取消它但不起作用。数据在对象内部有数组。函数,位于控制器内部,使用模型获取数据。

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'));
    $currentSizeArray = array();
}

数据输出如下:

Array(
[0] => stdClass Object
    (
        [size] => 060x090 1/5
        [url] => floki-861-50-lilac-20991
        [color] => 50-Lilac
    )

[1] => stdClass Object
    (
        [size] => 080x150
        [url] => floki-861-50-lilac-20992
        [color] => 50-Lilac
    )

[2] => stdClass Object
    (
        [size] => 080x150
        [url] => floki-861-60-white-20134
        [color] => 60-White
    )

[3] => stdClass Object
    (
        [size] => 080x150
        [url] => floki-861-70-beige-20140
        [color] => 70-Beige
    )

[4] => stdClass Object
    (
        [size] => 080x150
        [url] => floki-861-95-silver-21002
        [color] => 95-Silver
    )

[5] => stdClass Object
    (
        [size] => 080x150
        [url] => floki-861-99-anthracite-20146
        [color] => 99-Anthracite
    )

[6] => stdClass Object
    (
        [size] => 120x120 round
        [url] => floki-861-50-lilac-20993
        [color] => 50-Lilac
    )

[7] => stdClass Object
    (
        [size] => 120x120 round
        [url] => floki-861-60-white-20138
        [color] => 60-White
    )
)

我试过了,我可以删除它:

   foreach ($currentSizeData as $sizeData) {
        if (preg_match("/(round)/", $sizeData->size)) {
            unset($currentSizeData[$currentSizeArrayCount]);
        }
        $currentSizeArrayCount++;
    }

我需要预先添加已删除的索引。我需要添加相同的格式。

【问题讨论】:

  • 到目前为止你尝试过什么?

标签: php arrays codeigniter object


【解决方案1】:

不建议遍历所有数据集。

但是有两种解决方案。首先是取消设置具有特定条件的数组元素,然后将这些元素取消移动到主数组:

foreach ($currentSizeData as $key => $ar) {
    if (strpos($ar->size, 'round') !== false) {
        $shift[] = $ar;
        unset($currentSizeData[$key]);
    }
}

array_unshift($currentSizeData, ...$shift);

另一种方法是使用usort

usort($currentSizeData, function ($a, $b) {
    return strpos($a->size, 'round') === false;
});

【讨论】:

  • 您的帮助。第一个解决方案看起来对我来说只是不同的格式,但是当我在 foreach 中循环“移位”时,它给了我相同的格式。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 2014-08-26
  • 2014-09-24
  • 2014-02-24
  • 1970-01-01
  • 2014-01-01
相关资源
最近更新 更多