开发者

How Can I Set Up a "Where" Statement with a PHP Array

开发者 https://www.devze.com 2022-12-31 21:54 出处:网络
Am I able to apply \"where\" statements to PHP arrays, similar to how 开发者_JAVA技巧I would be able to apply a \"where\" statement to a MySQL query?

Am I able to apply "where" statements to PHP arrays, similar to how 开发者_JAVA技巧I would be able to apply a "where" statement to a MySQL query?

For example, suppose I have the following array:

$recordset = array(
array('host' => 1, 'country' => 'fr', 'year' => 2010,
    'month' => 1, 'clicks' => 123, 'users' => 4),
array('host' => 1, 'country' => 'fr', 'year' => 2010,
    'month' => 2, 'clicks' => 134, 'users' => 5),
array('host' => 1, 'country' => 'fr', 'year' => 2010,
    'month' => 3, 'clicks' => 341, 'users' => 2),
array('host' => 1, 'country' => 'es', 'year' => 2010,
    'month' => 1, 'clicks' => 113, 'users' => 4),
array('host' => 1, 'country' => 'es', 'year' => 2010,
    'month' => 2, 'clicks' => 234, 'users' => 5),
array('host' => 1, 'country' => 'es', 'year' => 2010,
    'month' => 3, 'clicks' => 421, 'users' => 2),
array('host' => 1, 'country' => 'es', 'year' => 2010,
    'month' => 4, 'clicks' => 22,  'users' => 3),
array('host' => 2, 'country' => 'es', 'year' => 2010,
    'month' => 1, 'clicks' => 111, 'users' => 2),
array('host' => 2, 'country' => 'es', 'year' => 2010,
    'month' => 2, 'clicks' => 2,   'users' => 4),
array('host' => 3, 'country' => 'es', 'year' => 2010,
    'month' => 3, 'clicks' => 34,  'users' => 2),
array('host' => 3, 'country' => 'es', 'year' => 2010,
    'month' => 4, 'clicks' => 1,   'users' => 1),);

How can I limit the output to only show the keys and values related to 'host' 1 and 'country' fr?

Any help would be great.


You can use array_filter() to get back a new array containing only the elements of the original which pass a certain test. Just define the test as a function which takes an element and returns either true or false, and then pass the array and the function (or function name) to array_filter.

The examples on the manual page should make it fairly obvious how it works.


As Amber said, array_filter is ideal for this. In combination with lambdas, you can make it fairly concise:

$output = array_filter($recordset, 
            function($el){return $el["host"] == 1 && $el["country"] == 'fr';});
0

精彩评论

暂无评论...
验证码 换一张
取 消