Php,我需要删除特定的文本在数组,后来我需要前置它



如果size index包含'round',我需要删除该索引并将其添加到数组中。因为圆的尺寸应该放在第一位。我尝试了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++;
}

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

不建议遍历所有数据集

然而,有两种解决方案。第一种是取消对具有特定条件的数组元素的设置,然后将这些元素移到主数组中:

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;
});