按字符串过滤数组并分成2个数组

时间:2018-08-21 11:23:54

标签: php arrays array-filter

我有一个像这样的数组

Array ( [operator_15] => 3 [fiter_15] => 4 [operator_17] => 5 [fiter_17] => 5 [operator_19] => 4 [fiter_19] => 2 )

我想将此阵列分成2个阵列:

  1. 密钥从fiter_
  2. 开始
  3. 密钥从operator_
  4. 开始

我使用了数组过滤器,但它不起作用。还有其他选择吗?

$array = array_filter($fitered_values, function($key) {
            return strpos($key, 'fiter_') === 0;
        });

3 个答案:

答案 0 :(得分:5)

只需使用strpos和substr循环_之前的数组和子字符串,然后就可以像这样将它们过滤到新数组中。
此方法也适用于新的数组键,请参见示例:

$arr = array ( "operator_15" => 3, 
               "fiter_15" => 4, 
               "operator_17" => 5, 
               "fiter_17" => 5, 
               "somethingelse_12" => 99 // <--- Notice this line.
              );

foreach($arr as $key => $val){
    $subarr = substr($key,0, strpos($key, "_"));
    $new[$subarr][$key] = $val;
}

var_dump($new);

输出:

array(3) {
["operator"]=>
  array(2) {
    ["operator_15"]=>
    int(3)
    ["operator_17"]=>
    int(5)
  }
  ["fiter"]=>
  array(2) {
    ["fiter_15"]=>
    int(4)
    ["fiter_17"]=>
    int(5)
  }
  ["somethingelse"]=>  // <-- is here now in it's own group with no code added
  array(1) {
    ["somethingelse_12"]=>
    int(99)
  }
}

答案 1 :(得分:3)

在下面尝试一下,看看它是否可以解决您的问题

$array = array ( 
    'operator_15' => 3,
    'fiter_15' => 4,
    'operator_17' => 5,
    'fiter_17' => 5,
    'operator_19' => 4,
    'fiter_19' => 2 );

$operator=array();
$filter=array();

foreach($array as $key => $value){
    if (strpos($key, 'operator_') !== false) {
        $operator[$key] = $value;
    }

    if (strpos($key, 'fiter_') !== false) {
        $filter[$key] = $value;
    }   
}

print_r($operator);
print_r($filter);

答案 2 :(得分:0)

这是一个有效的示例:

$a = array ( 'operator_15' => 3, 'fiter_15' => 4, 'operator_17' => 5, 'fiter_17' => 5, 'operator_19' => 4, 'fiter_19' => 2 );
$fiter_array = array();
$operator_array = array();
foreach($a as $key => $val)
{
    if(strpos($key, 'fiter') !== false)
    {
        array_push($fiter_array, $a[$key]);
        // or if you want to maintain the key
        $fiter_array[$key] = $val;
    }
    else
    {
        array_push($operator_array, $a[$key]);
        // or if you want to maintain the key
        $operator_array[$key] = $val;
    }
};
var_dump($fiter_array);
var_dump($operator_array);