按特定值在数组中搜索

时间:2015-04-03 15:35:36

标签: php arrays search

我有一个这样的数组:

// The Main(Mother) array 
[id] => 1
[content] => co1
[author_id] => 2
[date] => 1
[parent_id] => 0
[childs] => Array
    (

        [0] => Array
            (
                // The first child 
                [id] => 1
                [content] => co1
                [author_id] => 3
                [parent_id] => 1
                [childs] => Array
                    (
                    )

            )
      [1] => Array
                (
                    // The second child 
                    [id] => 2
                    [content] => co2
                    [author_id] => 2
                    [parent_id] => 2
                    [childs] => Array
                        (
                        )

                )
       // and another child .....

    )

现在我想在孩子中搜索:

search query : number of child where [id] = 1  ?  => php tell me [0] 
or
search query : number of child where [id] = 2  ?  => php tell me [1] 
or
search query : number of child where [content] => co1  ?  => php tell me [1] 

我测试了array_search();,但它在所有参数之间进行搜索!

我该怎么做? 例如,SQL中有这样的查询:

SELECT id FROM table WHERE date='2015.5.2'

请注意我无法使用array_search(),因为它只是在所有内容之间进行搜索,而我只想找到id = 1中的孩子的号码。

我知道我可以使用foreach循环执行此操作,但我想找到一种优化代码的干燥方法。我想在PHP和数组中使用这样的东西。

1 个答案:

答案 0 :(得分:0)

从array_search()PHP文档页面https://php.net/manual/en/function.array-search.php#116635查看此答案,它可能会解决您的问题。