PHP 搜索嵌套数组以按名称删除元素 [英] PHP searching through a nested array to delete an element by name

查看:29
本文介绍了PHP 搜索嵌套数组以按名称删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未真正使用过 PHP 数组,因为我过去只使用过数据库,所以我的视野有点开阔.基本上我有一个简单的嵌套数组,其中每个元素都有一个名称"和一些其他值.我正在尝试搜索数组,它是对象的一部分.我在这里查看了许多以前的问题,但无法使其正常工作,尽管在其他情况下没有涉及对象.我一直在尝试使用针/干草堆"类型的示例,但还没有让它工作.

I've never really used PHP arrays before as I've just used a database in the past so I'm broadening my horizons a little. Basically I have a simple nested array where each element has a 'name' and some other values. I'm trying to search through the array, which is part of an object. I've looked through a number of previous questions on here and can't get it working, although in the other cases there haven't been objects involved. I've been trying to use a 'needle/haystack' type example but haven't got it working yet.

所以在我的 People 类中,我们有:

So in my People class we have among other things:

public $peopleArray;  // this is the array and will be protected once working

// and this is the example search function im trying to modify
public function findPerson($needle, $haystack)
{
    foreach($haystack as $key=>$value)
    {
        if(is_array($value) && array_search($needle, $value) !== false)
        {
            return $key;
        }
    }
    return 'false';
}

然后称之为我目前拥有的:

And then to call this I currently have:

$searchResult = $People->findPerson('Bob',$people->peopleArray,'name');

我不确定我是否只是将自己与 $needle 和 $value 混淆了 - 我需要在搜索函数中传递名称值,所以我在函数参数中确实有 $value,但这仍然什么也没回.此外,我不是 100% 是否需要修改$key=>$value",因为 $key 未定义.

I'm not sure if I'm just confusing myself with what the $needle and $value - I need to pass the name value in the search function, so I did have $value in the function arguments, but this still returned nothing. Also I'm not 100% on whether '$key=>$value' needs modifying as $key is undefined.

在此先感谢您的帮助.

加法 - 数组的print_r:

Addition - print_r of the array:

Array ( [0] => Person Object ( [id:protected] => 1 [name] => Bob [gender] => m ) 
[1] => Person Object ( [id:protected] => 2 [name] => Denise [gender] => f ) 
[2] => Person Object ( [id:protected] => 3 [name] => Madge [gender] => f ) ) 

推荐答案

好吧,如果你必须发布一个示例数组,这会容易得多,但我要试一试这个问题.

Ok this would be a lot easier if you had to post an example array, but I'm going to give this question a shot.

对我来说,您似乎在遍历二维数组(嵌套数组).

To me it seems you are looping through a 2D array (nested array).

我会像这样循环遍历多维数组:

I would loop through multidimensional arrays like such:

for($array as $key => $2ndArray){
    for($2ndArray as $2ndKey => $value){
        if($value == $needle){
           return true;
        }
    }
}

希望能帮到你

这篇关于PHP 搜索嵌套数组以按名称删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆