Preg匹配数组键

时间:2016-02-10 12:04:22

标签: php arrays

我喜欢这样:

$data = array(
    "City_0" => "London",
    "City_1" => "Paris",
    "City_2" => "Lisbon",
    "City_3" => "Berlin"
    );

加上同一个数组中的其他一些数据。

用户只会选择其中一个,我需要的是:

  1. 使用preg_match检查以获取以“city _”
  2. 开头的所有键
  3. 找到具有值的键(它不为空),取该值
  4. 将其分配给新密钥
  5. 删除所有“city_”键
  6. 将新密钥添加到名为“chosen_city”的数组中,该名称将包含该值
  7. 我尝试了什么:

    foreach ($data as $key => $value) {
        $matches = preg_match('/city_/i', $key);
    
        if ($value != "") {
            $newValue = $value;
    
            break;
        }
    }
    
    $data['chosen_city'] = $newValue;
    
    
    print_r($data);
    

    这部分有效,如何在if语句中从数组中删除所有以前的“city_”键?

    注意: 我在数组中有其他键,我也不想删除它们。

    输入数组:

    $data = array(
            "City_0" => "London",
            "City_1" => "Paris",
            "City_2" => "Lisbon",
            "City_3" => "Berlin",
            "distance" => "5 km",
            "days" =>   "7",
            "tickets" => "2",
            "discount" => "10%",
            );
    

    预期产出:

    $data = array(
                "chosen_city" => "Berlin",
                "distance" => "5 km",
                "days" =>   "7",
                "tickets" => "2",
                "discount" => "10%",
                );
    

    感谢。

3 个答案:

答案 0 :(得分:1)

请输入未设置的示例代码:

$data = array( "City_0" => "London", "City_1" => "Paris", "City_2" => "Lisbon", "City_3" => "Berlin");
foreach($data as $key => $value){
    $matches = preg_match('/city_/i', $key);

    if($matches && $value != ""){
        $newValue = $value;
        unset($data[$key]);
    }elseif($matches){
        unset($data[$key]);
    }

}

$data['chosen_city'] = $newValue;

答案 1 :(得分:0)

在这种情况下,

preg_ *有点矫枉过正 - 你可以使用strpos并且它也可以正常工作

然而,问题是如何删除city_ *键',为此,只需使用unset():

foreach($data as $key => $value){
    $matches = preg_match('/city_/i', $key);

    if($value != ""){
        $newValue = $value;
        unset($data[$key]); //Remove this item from the array
        break;
    }
}

$data['chosen_city'] = $newValue;


print_r($data);

答案 2 :(得分:0)

$data = array(
    "City_0" => "London",
    "City_1" => "Paris",
    "City_2" => "Lisbon",
    "City_3" => "Berlin",
    "distance" => "5 km",
    "days" =>   "7",
    "tickets" => "2",
    "discount" => "10%",
);

$value = 'Berlin';
if (array_search($value, $data)) {
    $data['chosen_city'] = $value;
    foreach ($data as $key=>$val) {
        if (stripos($key, 'city_')===0) {
            unset($data[$key]);
        }
    }
}

结果:

array(5) {
  'distance' =>
  string(4) "5 km"
  'days' =>
  string(1) "7"
  'tickets' =>
  string(1) "2"
  'discount' =>
  string(3) "10%"
  'chosen_city' =>
  string(6) "Berlin"
}

如果你使用PHP> = 5.6,可能你可以使用(我没有测试过这段代码)

$city = array_search($value, $data);
if ($city) {
    $data['chosen_city'] = $value;
    $data = array_filter($data,function($key,$val){return stripos($key,'city_')===false;},ARRAY_FILTER_USE_BOTH);
}