标签:style blog color 使用 ar for sp div log
一个数组$a0有N个元素,要将其中第3个元素,排在数组的首位。
第一种做法是:
取出第3个元素,赋值给变量$a
unset 第3个元素
array_unshift 将$a添加到数组头部。
如果是数字下标的数组,这样是可以的。可如果是字符串做为下标,array_unshift会破坏下标,都变成了数字,以0开始计数。
解决方案为:
取出第3个元素,定义成一个单一数组 $a1
unset第3个元素,更新数组$a0
array_merge($a1,$a0)。
使用 array_merge 不会破坏数组下标。
示例:
<?php $array1 = array ( 0 => array ( ‘top‘ => ‘true‘, ‘path‘ => ‘cPath=9‘, ‘current‘ => false, ‘name‘ => ‘Women‘, ‘image‘ => NULL, ‘has_sub_cat‘ => true, ), 1 => array ( ‘top‘ => ‘true‘, ‘path‘ => ‘cPath=10‘, ‘current‘ => false, ‘name‘ => ‘Men‘, ‘image‘ => NULL, ‘has_sub_cat‘ => false, ), 2 => array ( ‘top‘ => ‘true‘, ‘path‘ => ‘cPath=1‘, ‘current‘ => false, ‘name‘ => ‘Accessories‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => false, ), 3 => array ( ‘top‘ => ‘true‘, ‘path‘ => ‘cPath=2‘, ‘current‘ => false, ‘name‘ => ‘New Arrival‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => false, ), 4 => array ( ‘top‘ => ‘true‘, ‘path‘ => ‘cPath=4‘, ‘current‘ => true, ‘name‘ => ‘Styles‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => true, ), 5 => array ( ‘top‘ => ‘false‘, ‘path‘ => ‘cPath=4_5‘, ‘current‘ => false, ‘name‘ => ‘Basketball Shoes‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => false, ), 6 => array ( ‘top‘ => ‘false‘, ‘path‘ => ‘cPath=4_6‘, ‘current‘ => false, ‘name‘ => ‘Football Shoes‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => false, ), 7 => array ( ‘top‘ => ‘false‘, ‘path‘ => ‘cPath=4_7‘, ‘current‘ => true, ‘name‘ => ‘Tennis Shoes‘, ‘image‘ => ‘‘, ‘has_sub_cat‘ => false, ) ); var_export($array1); echo "<br /><br /><br />\n\r"; $temp_array = array(); global $temp_array,$rootcid; foreach($array1 as $k=>$v){ if($v[‘current‘] == true){ $rootcids = explode(‘_‘, str_replace(‘cPath=‘, ‘‘, $v[‘path‘])); $rootcid = $rootcids[0]; break; } } foreach($array1 as $k=>$v){ $ifrootcid = explode(‘_‘, str_replace(‘cPath=‘, ‘‘, $v[‘path‘])); if($rootcid==$ifrootcid[0]){ $temp_array[] = $v; unset($array1[$k]); } } //$array1 = array_values($array1); var_export($array1); echo "<br /><br /><br />\n\r"; //var_export($temp_array); $array1 = array_merge($temp_array, $array1); var_export($array1); ?>
打完收工。
标签:style blog color 使用 ar for sp div log
原文地址:http://www.cnblogs.com/afish/p/4017645.html