我想對foreach中的數組進行排序。 以下是我的代碼:在foreach中排序數組
<?php $_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>
<?php $i = 0; foreach ($_images as $_image){ $i++; ?>
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(300,300); ?>" style="width:50px;height:50px;">
<?php } ?>
我需要在正確的順序打印出圖像。
$_image[position_default]
我一直在使用Ksort嘗試:它應該值進行排序
<?php $_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>
<?php $i = 0; foreach ($_images as $_image){ $i++; ?>
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(300,300); ?>" style="width:50px;height:50px;">
<?php ksort($_image['position']); ?>
<?php } ?>
不過,這並不在他們的所有排序。也許我不正確使用它? 有什麼建議嗎? :)
的$ _image一些輸出:
[224] => Varien_Object Object
(
[_data:protected] => Array
(
[value_id] => 224
[file] => /s/a/salty_fred_kn_kket.jpg
[label] =>
[position] => 2
[disabled] => 0
[label_default] =>
[position_default] => 2
[disabled_default] => 0
[url] => http://webshop.simplychocolate.dk/media/catalog/product/s/a/salty_fred_kn_kket.jpg
[id] => 224
[path] => /home/www/webshop.simplychocolate.dk/media/catalog/product/s/a/salty_fred_kn_kket.jpg
)
[_hasDataChanges:protected] =>
[_origData:protected] =>
[_idFieldName:protected] =>
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)
[247] => Varien_Object Object
(
[_data:protected] => Array
(
[value_id] => 247
[file] => /i/m/image_150.jpg
[label] =>
[position] => 3
[disabled] => 0
[label_default] =>
[position_default] => 1
[disabled_default] => 0
[url] => http://webshop.simplychocolate.dk/media/catalog/product/i/m/image_150.jpg
[id] => 247
[path] => /home/www/webshop.simplychocolate.dk/media/catalog/product/i/m/image_150.jpg
)
[_hasDataChanges:protected] =>
[_origData:protected] =>
[_idFieldName:protected] =>
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)
[258] => Varien_Object Object
(
[_data:protected] => Array
(
[value_id] => 258
[file] => /a/v/avatar.png
[label] =>
[position] => 3
[disabled] => 0
[label_default] =>
[position_default] => 3
[disabled_default] => 0
[url] => http://webshop.simplychocolate.dk/media/catalog/product/a/v/avatar.png
[id] => 258
[path] => /home/www/webshop.simplychocolate.dk/media/catalog/product/a/v/avatar.png
)
[_hasDataChanges:protected] =>
[_origData:protected] =>
[_idFieldName:protected] =>
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
)
您需要在'foreach'循環之前對數組進行排序。 – jeroen
我不知道你是否想用'$ _image ['position']'鍵或$ _images [key]'鍵進行排序? – h2ooooooo
$ _image將會是一個單一的圖像。排序單元素數組毫無意義。您需要ksort $ _images,並且由於您正在排序特定的密鑰,因此可能需要使用uksort。 –