从2个现有数组创建新数组 - 其中一个是其他关键值

时间:2015-07-09 14:45:51

标签: php arrays

我的主要"数组看起来像这样 - var_dump($ main)

[zlec_addresoperator] => and
[filtervalue0] => Test
[filtercondition0] => CONTAINS
[filteroperator0] => 1
[filterdatafield0] => zlec_addres
[zlec_nroperator] => and
[filtervalue1] => SecondVal
[filtercondition1] => CONTAINS
[filteroperator1] => 1
[filterdatafield1] => zlec_nr

我想构建一个新数组

array( filterdatafield0 = > filtervalue0 , filterdatafield1 = > filtervalue1)

首先,我决定使用以下代码过滤掉我想要的内容。创建新数组以保存数据,因此$ arraykeys将包含filterdatafield。{1,2}值。在这种情况下,它将是zlec_addres和zlec_nr。 第二个$ arrayvalue将保留filtervalue。{1,2},这是过滤器的值。

$newarray = array();
$arraykeys = array();
$arrayvalue = array();

foreach($_GET as $key => $value):

 if(preg_match("/^filterdatafield.{1,2}$/",$key)>0) {
        // $key is matched by the regex
        $arrayvalue[] = $value;
    }


    if(preg_match("/^filtervalue.{1,2}$/",$key)>0) {
        // $key is matched by the regex
        $arraykeys[] = $key;
    }
endforeach;
foreach($arraykeys as $a){
    $newarray[$a] = $arrayvalue;
}

所以期望的输出是

array(
zlec_addres => 'Test', zlec_nr = 'SecondVal'
)

现在是

array(12) {
  ["filtervalue0"]=>
  array(12) {
    [0]=>
    string(11) "zlec_addres"
    [1]=>
    string(7) "zlec_nr"
...
  }
  ["filtervalue1"]=>
  array(12) {
    [0]=>
    string(11) "zlec_addres"
    [1]=>
    string(7) "zlec_nr"
...
  }

2 个答案:

答案 0 :(得分:1)

    $newarray = array();
    $arraykeys = array();
    $arrayvalue = array();

    foreach($_GET as $key => $value){

     if(preg_match("/^filterdatafield.{1,2}$/",$key)>0) {
            // $key is matched by the regex
            $arraykeys[] = $value;
        }


        if(preg_match("/^filtervalue.{1,2}$/",$key)>0) {
            // $key is matched by the regex
            $arrayvalues[] = $value;
        }
    }
$newArray = array_combine($arraykeys, $arrayvalues);

答案 1 :(得分:0)

这应该适合你:

只需抓住您想要的密钥preg_grep(),然后将array_combine()两个阵列放在一起。

<?php

    $arr = [
        "zlec_addresoperator" => "and",
        "filtervalue0" => "Test",
        "filtercondition0" => "CONTAINS",
        "filteroperator0" => "1",
        "filterdatafield0" => "zlec_addres",
        "zlec_nroperator" => "and",
        "filtervalue1" => "SecondVal",
        "filtercondition1" => "CONTAINS",
        "filteroperator1" => "1",
        "filterdatafield1" => "zlec_nr",
    ];

    $newArray = array_combine(
        preg_grep("/^filterdatafield\d+$/", array_keys($arr)),
        preg_grep("/^filtervalue\d+$/", array_keys($arr))
    );

    print_r($newArray);

?>

输出:

Array
(
    [filterdatafield0] => filtervalue0
    [filterdatafield1] => filtervalue1
)