php将键映射到多维数组

时间:2014-05-29 00:44:01

标签: php arrays multidimensional-array key-value

非常新的PHP。我将不胜感激,任何人都可以提供有关使用php映射此数组中的值的指导,这是var_dump的输出

array(3) {
  ["k"]=>
  string(78) "method,from_tag,to_tag,callid,sip_code,sip_reason,time,from_user,to_user,token"
  ["v"]=>
  string(326) "BYE,gFNk8BZBg,B2B.269.327,KjmE8oPOV1,200,OK,Wed May 28 23:11:43 2014
,patientdemo1.gmail,sip:join.me@192.168.1.20:5060;transport=udp,037d30d7239a0a16a658474822c3c9acf7995ac781a9c1c8b4b1a7361f24400d71216209c18eff8b8b0400bb55890bb2a78eb3064b603e6ac4e270b76c36be0e365bf096e426cfb6621aac13fdec54e7bbce74b3d63244b4cb622b16e27da1c4"
  ["query_type"]=>
  string(6) "insert"
}

您可能已经注意到列键位于第一个数组中,键为“k”,值为“v”

我需要通过引用“k”

中的键来拉出其中一些值

1 个答案:

答案 0 :(得分:1)

如评论中所述。您可以使用explode()keysvalues分别设置到其数组中。

完成如下:

<?php

$things = array(
'k' => 'method,from_tag,to_tag,callid,sip_code,sip_reason,time,from_user,to_user,token',
'v' => 'BYE,gFNk8BZBg,B2B.269.327,KjmE8oPOV1,200,OK,Wed May 28 23:11:43 2014
,patientdemo1.gmail,sip:join.me@192.168.1.20:5060;transport=udp,037d30d7239a0a16a658474822c3c9acf7995ac781a9c1c8b4b1a7361f24400d71216209c18eff8b8b0400bb55890bb2a78eb3064b603e6ac4e270b76c36be0e365bf096e426cfb6621aac13fdec54e7bbce74b3d63244b4cb622b16e27da1c4'
);

$keys = explode(',', $things['k']);
$values = explode(',', $things['v']);

?>

返回:

<强>键

Array
(
    [0] => method
    [1] => from_tag
    [2] => to_tag
    [3] => callid
    [4] => sip_code
    [5] => sip_reason
    [6] => time
    [7] => from_user
    [8] => to_user
    [9] => token
)

<强>值

Array
(
    [0] => BYE
    [1] => gFNk8BZBg
    [2] => B2B.269.327
    [3] => KjmE8oPOV1
    [4] => 200
    [5] => OK
    [6] => Wed May 28 23:11:43 2014

    [7] => patientdemo1.gmail
    [8] => sip:join.me@192.168.1.20:5060;transport=udp
    [9] => 037d30d7239a0a16a658474822c3c9acf7995ac781a9c1c8b4b1a7361f24400d71216209c18eff8b8b0400bb55890bb2a78eb3064b603e6ac4e270b76c36be0e365bf096e426cfb6621aac13fdec54e7bbce74b3d63244b4cb622b16e27da1c4
)

现在你只需要使用foreach()

循环使用这些值
$data = array();
foreach($keys as $i => $key) {
    $data[$key] = $values[$i];
}

哪会产生你的最终输出:

Array
(
    [method] => BYE
    [from_tag] => gFNk8BZBg
    [to_tag] => B2B.269.327
    [callid] => KjmE8oPOV1
    [sip_code] => 200
    [sip_reason] => OK
    [time] => Wed May 28 23:11:43 2014

    [from_user] => patientdemo1.gmail
    [to_user] => sip:join.me@192.168.1.20:5060;transport=udp
    [token] => 037d30d7239a0a16a658474822c3c9acf7995ac781a9c1c8b4b1a7361f24400d71216209c18eff8b8b0400bb55890bb2a78eb3064b603e6ac4e270b76c36be0e365bf096e426cfb6621aac13fdec54e7bbce74b3d63244b4cb622b16e27da1c4
)

Working Example


脚注

这可能不是处理/做你想做的事情最有效的方法。您应该重新考虑如何创建具有列/值的第一个数组,并重新构建以满足您的需求。

应该 使用array_combine()代替!


如果这回答了你的问题,只需点击左边的箭头直到它是绿色:)将此问题标记为已回答!