怎么用爆炸?

时间:2011-11-24 16:43:55

标签: php arrays cookies explode

所以我有这个php:

<?php
if (isset($_COOKIE["currentsearchctrl"])) {
    $cookz = $_COOKIE["currentsearchctrl"];
    $data = explode(';', $cookz, -1);
    $newdata = array();

    foreach($data as $value){
        $newdata[] = explode(':', $value, -1);
    }    
    print_r($newdata);

} else { }
?>

php正在读取的cookie:

  

%20Rod%20Stewart%20%3A%2059088763306%3B%20Led%20Zeppelin%20Official%20%3A%20131572223581891%3B%20Lynyrd%20Skynyrd%20%3A%206983887641%3B%20Black%20Sabbath%20%3A% 2056848544614%3B

但是&#39; print_r&#39;输出:

Array ( [0] => Array ( [0] => Rod Stewart ) [1] => Array ( [0] => Led Zeppelin Official ) [2] => Array ( [0] => Lynyrd Skynyrd ) [3] => Array ( [0] => Black Sabbath ) )

&#39; id&#39;不见了。我需要它。数组([0] =&gt;数组([0] =&gt;罗德斯图尔特,[1] =&gt; 1200420)[1] =&gt;数组([0] =&gt; Led Zeppelin官方,[1] =&gt; ; 110024294)...

为了提供帮助,这是print_r($ data)的输出:

Array ( [0] => Rod Stewart : 59088763306 [1] => Led Zeppelin Official : 131572223581891 [2] => Lynyrd Skynyrd : 6983887641 [3] => Black Sabbath : 56848544614 )

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

我认为这就是你要做的事情:

$data = array (0 => "Rod Stewart : 59088763306", 1 => "Led Zeppelin Official : 131572223581891", 2 => "Lynyrd Skynyrd : 6983887641", 3 => "Black Sabbath : 56848544614" );


$data = array_map(function($item){
    list($artist, $id) = explode(' : ', $item);
    return array('id'=>$id, 'artist'=>$artist);
}, $data);

print_r($data);

输出

Array
(
    [0] => Array
        (
            [id] => 59088763306
            [artist] => Rod Stewart
        )

    [1] => Array
        (
            [id] => 131572223581891
            [artist] => Led Zeppelin Official
        )

    [2] => Array
        (
            [id] => 6983887641
            [artist] => Lynyrd Skynyrd
        )

    [3] => Array
        (
            [id] => 56848544614
            [artist] => Black Sabbath
        )

)

答案 1 :(得分:1)

为什么不尝试使用正则表达式?

<?php
if (isset($_COOKIE["currentsearchctrl"])) {
    $cookz = urldecode($_COOKIE["currentsearchctrl"]);
    preg_match_all("#(?P<artist>(?:\w|\s)+)\s:\s(?P<id>\d+)#", $cookz, $matchs, PREG_SET_ORDER);    
    print_r($matchs);
} else { }
?>
编辑:对不起我没注意到名字不完整

示例:preg_match_all

答案 2 :(得分:0)

使用serialize()和unserialize()

$data = serialize($cookz);

序列化字符串可确保您将精确的structire存储到字符串中以便稍后恢复。