我正在设法从以前的数组中创建多维数组,然后将其按日期顺序排序。
目前,我的数组看起来如下:
array(5) {
[0]=> string(161) "2013-09-18~Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors~ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
[1]=> string(93) " 2010-10-20~Taking A Closer Look At Tech Conferences~taking-a-closer-look-at-tech-conferences"
[2]=> string(71) " 2014-10-19~Wayfinding For The Mobile Web~wayfinding-for-the-mobile-web" [3]=> string(60) " 2014-05-15~Freebie: Icons Of Autumn~freebie-icons-of-autumn"
[4]=> string(1) " "
}现在需要使用分隔符~进一步分解每个数组元素,我以前使用了foreach循环,但是这创建了3个不同的数据数组,而不是一个多维数组。
显然,我需要将每个值命名为$date、$title和$filename。
您将如何使用foreach循环来将其存储在一个多维数组中?这是我以前的经历
foreach ($masterpostlist as &$post){
$post = explode('~',$post);
}然后如何排序数组的日期部分,以便他们首先订购最新的?
发布于 2014-10-20 12:07:10
有很多方法可以做到这一点,但我认为我能想到的最短的(就编写代码而言)是使用array_map和usort。
首先,让我们确定我们必须做什么:
' '),我们需要去掉它,有些字符串包含前导空格,所以我们也必须去掉它首先,让我们对数据进行净化:
//assume $a is your array:
$a = array_filter(//gets rid of empty keys
array_map('trim', $a)//trim each element in $a
);接下来,让我们创建一个2D数组,其中每个索引包含一个带有键日期、标题和文件名的assoc数组
$x = array_map(
function($value)
{
return array_combine(
['date', 'title', 'filename'],//the keys
explode('~', $value)//the values
);
}, $a);最后,让我们来整理一下:
usort($x, function($a, $b)
{
$dateA = new DateTime($a['date']);//create a DateTime object from value
$dateB = new DateTime($b['date']);
if ($dateA == $dateB)//if both dates are the same
return 0;//don't move
return $dateA < $dateB ? 1 : -1;//descending order
});https://stackoverflow.com/questions/26464840
复制相似问题