我有两个数组。第一个直接来自我的原始数据。每个项目都是一个时间线的一个点。
print_r($items)
返回
Array
(
[0] => Array
(
[id] => 1173
[month] => January
[year] => 2013
[description] => This is a test
[link] => #
[image] => http://s3.amazonaws.com/stockpr-test-store/esph2/db/Timeline/1173/image_resized.jpg
)
[1] => Array
(
[id] => 1183
[month] => February
[year] => 2013
[description] => This is another test
[link] =>
)
[2] => Array
(
[id] => 1193
[month] => December
[year] => 2012
[description] => Testing another year
[link] => #
)
)
我有第二个数组,它从该数组中获得所有独特的年份。
print_r($years)
返回
Array
(
[0] => 2013
[2] => 2012
)
然后我如何度过这些年,然后每年归还与当年匹配的物品?
因此,对于2012年,我将从$items数组中获得[2]。对于2013,我将从$items数组中获得[0]和[1]。
我做错了吗?我想做的就是有这样的输出:
<h1>Timeline</h1>
<h2>2013</h2>
<ul>
<li>ID No. 1173</li>
<li>ID No. 1183</li>
</ul>
<h2>2012</h2>
<ul>
<li>ID No. 1193</li>
</ul>
编辑:
当前使用:
<? foreach($years as $year) : ?>
<div class="year row clearfix" id="y-$year">
<h3><span><?= $year ?></span></h3>
<? foreach($items as $item) : ?>
<? if($item['year'] == $year) : ?>
<div class="item span5">
<div class="padding">
<div class="text">
<h4><?= $item['month']?> <?= $item['year'] ?></h4>
<p><?= $item['description'] ?></p>
</div>
</div>
</div>
<? endif; ?>
<? endforeach; ?>
</div>
<? endforeach; ?>
但这似乎有点低效。据我所知,它每次试图输出一个项时都会遍历整个数组。
Heey,
我不确定我是否正确回答了你的问题,但你可以试试这个:
foreach($years as $aYear){
foreach($items as $aItem){
if($aItem['year'] == $aYear){
echo $aItem['description'];
}
}
}
这样的东西应该可以工作:
$years = ['2013','2012'];
for ($i = 0; $i < count($items); $i++)
{
if (in_array($years, $items[$i]['year']))
{
// do something with $items[$i]
}
}
//new array
$array2 = array();
foreach($array as $key)
{
$year = $array[$key]['year'];
//if year has already been used dont erase what's already in each part, add to it
if(array_key_exists($year, $array2))
{
array_push($array2[$year]['ids'],$array[$key]['id']);
//do rest
}
else
{
//if year hasnt been set as a key yet, then it's empty
$array2[$year]['ids'] = array($array[$key]['id']);
//do rest of your vars to populate it
}
}
如果你不喜欢硬编码键,那么可以使用foreach,然后再次检查是否使用。如果数组中的每个索引(如您的示例)可能都有相同的数字/键,那么在推送嵌套数组键之前,您必须仔细检查是否存在。(id,description,month)
数组2的输出应该是:
Array(
[2013] => array
(
[ids] => array
(
[0] => 1234
[1] => 5667
)
[months] => array
(
[0] => January
)
)
)
希望现在您的数组能够以更容易的方式进行组织。稍后将进行测试。