简体   繁体   English

在array_walk PHP中取消设置元素

[英]unset an element in array_walk PHP

I use array_walk to walk through an array "sessions", each time, I send my data ($uid) to the function. 我每次使用array_walk遍历数组“会话”时,都会将数据($ uid)发送给函数。

$uid = ...;

array_walk($sessions, array($this,'handle_each_session'), array('uid' => $uid));

in the function 'handle_each_session', there is another variable $package . 在“ handle_each_session”函数中,还有另一个变量$package If $package is empty, I will unset the element (remove the element from the array), otherwise I will put the $packag e into the element. 如果$package为空,我将取消设置元素(从数组中删除元素),否则将$packag e放入元素。

private function handle_each_session (& $s, $k, $data)
{
   $uid = $data['uid'];
   $s['uid'] = $uid;
   $package = $this->get_random_package($uid);

   //- if $package is not defined, then unset the element
   if (!isset($package) || empty($package))
   {
       unset($s);
       return;
   }

   //- otherwise put the package into the element
   $s['package'] = $package;
}

The result is the element $s is still there, is not removed from the sessions array. 结果是元素$s仍然存在,没有从会话数组中删除。

How can I archive that? 我该如何存档?

You can't do it this way. 你不能这样子。 Unset($s) does not destroy the $session var passed by reference. Unset($ s)不会破坏通过引用传递的$ session var。 It destroy the link between $s and $session. 它破坏了$ s和$ session之间的联系。 See documentation here: http://php.net/manual/en/language.references.unset.php 请参阅此处的文档: http : //php.net/manual/zh/language.references.unset.php

you better pass the whole $session by reference to a new "handle_session" function and go through the $session array in it. 您最好通过引用新的“ handle_session”函数传递整个$ session并通过其中的$ session数组。 using unset($session[$key]) should work. 使用unset($ session [$ key])应该可以。

Thanks @Bar-code to let me know, I cannot unset the element that way. 感谢@ Bar-code让我知道,我不能那样设置元素。

I use the array_filter to remove all elements with an empty package as follow: 我使用array_filter删除具有空包的所有元素,如下所示:

private function is_not_null_package($session)
{
        $package = $session['package'];
        $empty = (!isset($package) || empty($package));
        return (!$empty);
}

//- handle sessions
array_walk($sessions, array($this,'handle_each_session'), array('uId' => $uid));

//- filter sessions
//- remove all sessions with empty packages
$sessions = array_filter($sessions, array($this, 'is_not_null_package') );

It works for me. 这个对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM