根据搜索条件返回数组

时间:2013-06-16 01:43:07

标签: php css arrays multidimensional-array

我有一个这样的数组:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Product 1
        [color] => green
    )

[1] => Array
    (
        [id] => 2
        [1] => Product 12
        [color] => red
    )

[2] => Array
    (
        [id] => 3
        [1] => Product 3
        [color] => blue
    )
)

我希望能够根据颜色值过滤掉数据。功能如:

function filter_data($array, $color) {

}

我可以将$array$color参数作为字符串传递,而结果将是一个包含所有颜色为蓝色的项目的数组。

3 个答案:

答案 0 :(得分:1)

假设您的数据如下:

$data = array(
    array('id' => 1, 'name' => 'Product 1', 'color' => 'green'),
    array('id' => 2, 1 => 'Product 12', 'color' => 'red'),
    array('id' => 3, 1 => 'Product 3', 'color' => 'blue'),
);

我们可以遍历它,只返回基于color=__desired_color__的数组。

$final = array();
foreach ($data as $dat) {
    if ($dat['color'] == "blue") {
        $final[] = $dat;
    }
}

我希望你知道如何使这个功能。祝你好运!

答案 1 :(得分:1)

您应该看一下如何使用foreach loops。如果你想学习PHP,这将非常重要。

function filter_data($array, $color) {
  $results = array();
  foreach ($array as $data) {
    if ($data['color'] == $color) {
      $results[] = $data;
    }
  }
  return $results;
}

此函数只是迭代$array中的所有值,并检查每个子数组的color,看它是否与给定的$color匹配。

答案 2 :(得分:1)

继承人的功能......

它允许您输入数组,要过滤的键/字段以及要搜索的搜索词...

/*
*@param $arr = array  //array of your choosing
*@param $field  string  //key value of array to search through 
*@param $item   string  //Search term
*@return array  //returns filtered array
*/

function search($arr, $field, $item){
 $result = array();
 foreach ($arr as $val) {
     if ($val[$field] == $item) {
    $result[] = $val;
  }
 }
 return $result;
 }

然后就这样使用它......

search($yourarray, "color","blue");
相关问题