aron n
aron n

Reputation: 597

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%

Upvotes: 2

Views: 99

Answers (4)

arlomedia
arlomedia

Reputation: 9071

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

Upvotes: 1

Orbling
Orbling

Reputation: 20612

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;
}

Upvotes: 0

netcoder
netcoder

Reputation: 67735

This will get you an associative array:

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

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 838796

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.

Upvotes: 3

Related Questions