开发者

How do I split these arrays?

$data = "google,98%,bing,92%,searchengine,56%,seo,85%,search,94%";

I want split thsese and get final result

google = 98%
bing = 92开发者_如何学运维%
searchengine = 56%
seo = 85%
search = 94%


This will get you an associative array:

$out = array();
$parts = explode(',', $data);
for($i=0;$i<count($parts);$i++) {
   $out[$parts[$i]] = $parts[++$i];
}


If you want your output as a single string containing new lines you can use preg_replace:

$result = preg_replace('/([^,]*),([^,]*),?/', "$1 = $2\n", $data);

Output:

google = 98%
bing = 92%
searchengine = 56%
seo = 85%
search = 94%

See it working online at ideone.


Try this:

$data = "google,98%,bing,92%,searchengine,56%,seo,85%,search,94%";

preg_match_all("/(\w+),(\d+)%/", $data, $data_array, PREG_SET_ORDER);

foreach($data_array as $item) {
    print $item[1]." = ".$item[2]."%<br />";
}

The parsing all happens in one line; the only looping is in the output. You can do print_r($data_array) to see how the array is structured in case you want to do different things with the data.

Also, if you want the percent sign included in the data, you can move it to the inside of the second parentheses pair. But if you leave it out (and just display it upon output) it will be easier to perform calculations on the data if you need to


How about...

$data = "google,98%,bing,92%,searchengine,56%,seo,85%,search,94%";
$dataSet = array_combine(array_map(create_function('$entry', 'return $entry[0];'),
                                   array_chunk(explode(",", $data), 2)),
                         array_map(create_function('$entry', 'return $entry[1];'),
                                   array_chunk(explode(",", $data), 2)));

foreach ($dataSet as $cType => $cPercentage) {
    echo $cType . " = " . $cPercentage;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜