doubu5035 2009-12-15 21:45 采纳率: 100%
浏览 237
已采纳

在PHP中:如何将一个数组的子集过滤到另一个数组?

foreach ($myarray as $value)
  {
        if (strpos($value,'mysearchstring'))
             //add this $value to new array here
  }

Also where would the second array need to be declared and how?

  • 写回答

8条回答 默认 最新

  • douzhuiqiu4923 2009-12-15 21:48
    关注

    To avoid warnings, the second array should be declared like so

    $newArray = array();
    

    This could be incorporated into your code like so

    $newArray = array();
    foreach ($myarray as $value){
        if (strpos($value,'mysearchstring') !== false ){
             $newArray[] = $value;
        }
    }
    

    Your original code contained an error. strpos returns and false if it doesn't contain the needle, else it returns the index of the occurrence. So strpos($value,'mysearchstring') will return 0 if $value starts with 'mysearchstring' . As PHP will convert 0 to false and visa versa, it will not get added to the array if we use the standard comparisons, so we need to explicitly check that it is false without type conversion (converting 0 to false for example). To do this we use !== (Note the two =)s. This is represented in the code above.

    For more information on comparison operators in php, see the documentation.

    EDIT
    Regarding the commend and usage of [], it ads the new element to the end of the array

    The documentation states that:

    if no key is specified [in the square brackets], the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).

    So if we have an array

    $arr = array(5 => 1, 12 => 2);
    
    //doing this
    $arr[] = 56;
    
    //is exactly the same as doing
    $arr[13] = 56
    
    //As the maximum integer key is 12, so the new key is 13
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里