dongruan6001 2016-10-31 10:40
浏览 24
已采纳

PHP - 操作数组

I want to manipulate an array and i'm a bit stuck on how to proceed and hoping i can be pointed to the right direction

This is the array i currently have:

    array(10) { 
["gdlr-room-id"]=> string(4) "3595" 
["gdlr-check-in"]=> string(10) "2016-10-31"
["gdlr-night"]=> string(1) "1" 
["gdlr-check-out"]=> string(10) "2016-11-01" 
["gdlr-room-number"]=> string(1) "1" 
["gdlr-adult-number"]=> string(1) "1" 
["gdlr-children-number"]=> string(1) "1" 
["gdlr-resident"]=> string(8) "resident" 
["service"]=> string(19) "5061,5060" 
["service-amount"]=> string(7) "1,1" }

And this is what i want to achieve:

 array(10) { 
["gdlr-room-id"]=> array(1) { [0]=> string(4) "3595" }
["gdlr-check-in"]=> string(10) "2016-10-31"
["gdlr-night"]=> string(1) "1" 
["gdlr-check-out"]=> string(10) "2016-11-01" 
["gdlr-room-number"]=> string(1) "1"
["gdlr-adult-number"]=> array(1) { [0]=> string(1) "1" } 
["gdlr-children-number"]=> array(1) { [0]=> string(1) "1" }
["gdlr-resident"]=> string(8) "resident" 
["service"]=> array(2) { [0]=> string(4) "5061" [1]=> string(4) "5060" } 
["service-amount"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "1" } 
} 

If i can explain a bit more: if we take the key gdlr-room-id as an example: my current array represents a key, value pair as shown ["gdlr-room-id"]=> string(4) "3595" while my desired result is for the value to be inside another array as shown: ["gdlr-room-id"]=> array(1) { [0]=> string(4) "3595" }. This is not for all the key=>value pairs but only a select few as some would remain as they are e.g. ["gdlr-check-in"]=> string(10) "2016-10-31" is ok as it is

In summary, how do i take some values inside an array(as my current one is) and make some values be inside another array as i have explained above? and while we're at it, any suggestion how i can turn this ["service"]=> string(19) "5061,5060" into this: ["service"]=> array(2) { [0]=> string(4) "5061" [1]=> string(4) "5060" }? thanks

  • 写回答

2条回答 默认 最新

  • doutui839638 2016-10-31 10:57
    关注

    If you have a list of keys for which the value should be expanded into arrays, e.g.

    $expand_keys = array('gdlr-room-id', 'service');
    

    and multiple values are separated by commas, you could do something like

    foreach ($array as $key => $value) {
      if (in_array($key, $expand_keys)) {
        $array[$key] = explode(',', $value);
      }
    }
    

    This will check each key-value pair of your original array and explode its value into an array if the key is in the $expand_keys array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错