我通过ajax收集页面的展示次数,然后将它们存储在json文件中。循环正确插入新的页面对象。问题是,当我希望用新的印象更新当前页面对象时,我的循环创建一个新对象,而不是更新数组中已存在的对象的值。
工作流:
预期结果(刷新下面带有ID的网页后的示例)
[
{
id: "page-1",
impressions: 15
},
{
id: "page-2",
impressions: 3
},
{
id: "page-3",
impressions: 22
}
]
实际结果(具有相同ID的项目未更新,但已创建为新项目)
[
{
id: "page-1",
impressions: 4
},
{
id: "page-2",
impressions: 2
},
{
id: "page-1",
impressions: 3
},
{
id: "page-3",
impressions: 2
},
{
id: "page-1",
impressions: 2
}
{
id: "page-1",
impressions: 1
},
{
id: "page-2",
impressions: 1
},
{
id: "page-3",
impressions: 1
}
]
...
我的循环
// If array exists
if ($pages > -1) {
// Loop thro all the items
foreach ($pages as $item) {
// If item exists, update it. Else create a new one
if ($item -> id == $id) {
$item -> impressions = $item -> impressions + 1;
} else {
$pages[] = array(
'id' => $id,
'impressions' => 1
);
}
}
}
// else create new one
else {
$pages = array();
$pages[] = array(
'id' => $id,
'impressions' => 1
);
}
// Store the array in file
file_put_contents($url, json_encode($pages));
答案 0 :(得分:2)
包含评论的正确代码:
if ($pages > -1) {
$impression_found = false;
foreach ($pages as $item) {
if ($item -> id == $id) {
// you have found the impression - update it
$item -> impressions = $item -> impressions + 1;
$impression_found = true;
// you can even `break` foreach as you already found your impression:
break;
} else {
// DO NOTHING
}
}
// This is really a new impression, add it
if (!$impression_found) {
$pages[] = array(
'id' => $id,
'impressions' => 1
);
}
}