将项推入数组并替换php

将项推入数组并替换php,php,arrays,session,Php,Arrays,Session,我需要做一个这样的数组 $privateMsgIdArray = array("idlistener" => $idlistener, "maxMsgId" => $lastMsgId); 我需要将maxMsgId替换为相应的idlistener,如果我传递的idlistener不存在,则在数组中创建一个新条目 对于如何提取与idlistener对应的maxMsgId值,我有点困惑 换句话说,我只需要传递idlistener的新值一次,并在每次它们不等于对应的idlistener时

我需要做一个这样的数组

$privateMsgIdArray = array("idlistener" => $idlistener, "maxMsgId" => $lastMsgId);
我需要将maxMsgId替换为相应的idlistener,如果我传递的idlistener不存在,则在数组中创建一个新条目

对于如何提取与idlistener对应的maxMsgId值,我有点困惑

换句话说,我只需要传递idlistener的新值一次,并在每次它们不等于对应的idlistener时替换maxMsgId。 如果idlistener字段不存在,则创建它并将其推入数组

我将旧数组传递到会话中,并在当前运行中传递新数组。 运行后,我会更换它们

我相信这听起来有点令人困惑

e、 g 我们已经有了这样的阵列: [15] [200]

下一个调用maxMsgId是210 数组应该是 [15] [210]

下一次调用我们有一个新的侦听器id,其maxMsgId为30 数组应该是 [15][210]
[16] [30]

您应该能够通过快速循环完成此任务:

// your "new" values
$idListener = 15;
$maxMsgId = 210;

// loop over the array to see if it contains the `idlistener` you want
$end = count($privateMsgIdArray);
for ($i = 0; $i < $end; $i++) {
    if ($privateMsgIdArray[$i]['idlistener'] == $idListener) {
        // we found it! overwrite the `maxMsgId` field
        $privateMsgIdArray[$i]['maxMsgId'] = $maxMsgId;
        break;
    }
}
if ($i == $end) {
    // we reached the end of the array without finding the `$idListener`;
    // add a new entry =]
    $privateMsgIdArray[] = array(
        'idlistener' => $idListener,
        'maxMsgId' => $maxMsgId
    );
}

上述两种方法都可以转换为函数,使事情更具可移植性。

我相信这是可行的,谢谢:D,但我仍然不知道如何计算旧maxMsgId和新maxMsgId之间的差异。例如cached id和currect id。查看从那时起传递了多少条消息。@user3127632如果您使用上述任一方法,在找到值在数组中的位置后,您应该能够进行计算;例如,在第一个示例中,您可以在覆盖值之前在if语句中使用该值:$maxIdDifference=$maxMsgId-$privateMsgIdArray[$i]['maxMsgId'];。我相信我听起来很傻,但在我发布这篇文章之前的几个小时里,我都很困惑,我使用循环后的第二种方法,我使用这个$_会话['privateMessages']=$privateMsgIdArray;但是,当我使用此回显缓存数据时,没有显示任何内容:.$\u会话['privateMessages'][$idlistener]['maxMsgId'];这将显示新数据:echo newdata.$currentCount=$privateMsgArray[$\u会话['privateMessages'][$idlistener]['maxMsgId'];我想用会话缓存的数据和新的数据来做你所说的计算above@user3127632这个主题听起来很不一样,足以让你提出一个全新的问题,如果你想发布一个能够提供完整解释/代码格式等的问题,我也很乐意为你看一看,检查这里你喜欢吗
// key = idlistener, value = index in `$privateMsgIdArray`
$idCache = array(15 => 0, 16 => 1);

// check if the `$idListener` is in the cache
if (!isset($idCache[$idListener])) {
    // it's not; add a new entry
    $key = count($privateMsgIdArray);
    $privateMsgIdArray[$key] = array(
        'idlistener' => $idListener,
        'maxMsgId' => $maxMsgId
    );
    // add the new index into the cache
    $idCache[$idListener] = $key;
} else {
    // it is in the cache; pull the corresponding index and set the `maxMsgId` =]
    $privateMsgIdArray[$idCache[$idListener]]['maxMsgId'] = $maxMsgId;
}