dqsot35145 2016-02-10 12:04
浏览 48
已采纳

Preg_match数组键

I have it like this:

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

plus some other data in that same array.

User will select only one of these and what I need is:

  1. Check with preg_match to get all keys that starts with "city_"
  2. find key which has value (it is not empty), take that value
  3. assign it to new key
  4. remove all "city_" keys
  5. add new key to array with the name "chosen_city" which will contain that value

What I tried:

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

    if ($value != "") {
        $newValue = $value;

        break;
    }
}

$data['chosen_city'] = $newValue;


print_r($data);

This works partially, how can I remove all previous "city_" keys from array in that if statement?

NOTE: I have other keys in array, and I don't want to remove them as well.

Input array:

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

Expected output:

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

Thanks.

  • 写回答

3条回答 默认 最新

  • dsy6639 2016-02-10 12:11
    关注

    Please put unset for example code :

    $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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向