![](/img/trans.png)
[英]How can I convert 3-D multidimentional array to 1-D array as below where I want to insert last array's values into that particular array's keys?
[英]How can I convert a Google Tag Manager's Initial Traffic Source cookie values to an array?
我已经使用 UTMZ Cookie Replicator 的一些第三方代码为 Google 标签管理器安装了“cookie 创建”代码。 它设置 cookie 并开始为访问网站的用户收集初始流量来源。 我的网站是https://www.palmerstonmoving.ca 。
cookie 名称为InitialTrafficSource
,返回的值为
utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)
如何获取 cookie 返回的字符串值并将其转换为某种 PHP 代码,例如:
$utmcsr= 'direct',
$utmcmd= 'none',
$utmccn= 'not set',
有很多方法可以做到这一点,我想知道你为什么不尝试一种(例如使用基本的字符串函数)。
具有基本功能:
$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';
$result = [];
foreach (explode('|', $str) as $item) {
list($key, $val) = explode('=', $item);
$result[$key] = trim($val, '()');
}
print_r($result);
一种在|
上拆分字符串的方法并且使用格式化的字符串来提取每个项目的键/值:
$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';
$format = '%[^=]=(%[^)])';
$result = [];
foreach (explode('|', $str) as $v) {
[$key, $result[$key]] = sscanf($v, $format);
}
print_r($result);
以功能方式编写的相同:
$result = array_reduce(explode('|', $str), function ($c, $i) {
[$key, $c[$key]] = sscanf($i, '%[^=]=(%[^)]');
return $c;
}, []);
使用正则表达式:
$str = 'utmcsr=(direct)|utmcmd=(none)|utmccn=(not set)';
preg_match_all('~ (?<key> [^|=]+ ) = \( (?<val> [^)]* ) \) ~x', $str, $matches);
$result = array_combine($matches['key'], $matches['val']);
print_r($result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.