![](/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.