Explode string in PHP that contain brackets and semicolon - php

Problem:
I have a string that looks like this:
[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]
Question:
How can you get that string into this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

I will try with:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$output = array();
preg_match_all('\[(\d+)=>([\d,]+)\]', $input, $matches);
foreach ($matches as $group) {
$output[$group[1])] = explode(',', $group[2]);
}
// and print result out:
foreach ( $output as $key => $val ) {
echo $key . '<br/>';
foreach ( $val as $v ) {
echo ' ' . $v . '<br/>';
}
}

This code:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$regex = '~\[(?P<keys>\d)+=>(?P<values>(?:\d+,?)+)\]~';
$result = array();
if (preg_match_all($regex, $input, $matches)) {
foreach ($matches['keys'] as $key => $value) {
$result[$value] = explode(',', $matches['values'][$key]);
}
}
print_r($result);
Results to this:
Array
(
[1] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[5] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[9] => Array
(
[0] => 10
[1] => 11
[2] => 12
)
[3] => Array
(
[0] => 14
[1] => 15
)
[6] => Array
(
[0] => 17
[1] => 18
)
)

$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$str = explode("]", $str);
$finalResult = array();
foreach ($str as $element) {
if (!empty($element)) {
$element = substr($element, 1);
$element = explode("=>", $element);
// element[0] contains the key
$element[1] = explode(",", $element[1]);
$finalResult[$element[0]] = $element[1];
}
}
print_r($finalResult);

<?php
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$parts1 = explode("][",$str);
$parts1[0]=str_replace("[","",$parts1[0]);
$parts1[count($parts1)-1]=str_replace("]","",$parts1[count($parts1)-1]);
foreach($parts1 as $k=>$v){
$parts2[]=explode("=>",$v);
}
foreach($parts2 as $k=>$v){
echo "<div>".$v[0]."</div>";
foreach(explode(",",$v[1]) as $key=>$value){
echo "<div style='margin-left:20px'>".$value."</div>";
}
}
Output Would be

Using only str_replace():
$dict = array(
'=>' => "\n\t",
',' => "\n\t",
'][' => "\n",
'[' => '',
']' => '',
);
echo str_replace(array_keys($dict), array_values($dict), $str);
Will give the result you want.

Related

Add up the values of multiple occurrences of multiple strings in a multidimensional array in PHP

I've got a multidimensional array.
I need a way to tally up the total value when both the 1st and second strings in the array occur multiple times.
So for instance :
Gold Metallic = 22
Black Toscano = 26
etc...
Any ideas?
[0] => Array
(
[0] => Array
(
[0] => Black
[1] => Toscano
[2] => 14
)
[1] => Array
(
[0] => Gold
[1] => Metallic
[2] => 10
)
)
[1] => Array
(
[0] => Array
(
[0] => Gold
[1] => Metallic
[2] => 12
)
[1] => Array
(
[0] => Black
[1] => Toscano
[2] => 12
)
)
This just solves the problem for your data structure so you have to make sure that, in practice, every two items you will get a number. Hope you can learn something from this :)
$products = array(
array(
array("Black", "Toscano", 14),
array("Gold", "Metallic", 10)
),
array(
array("Black", "Toscano", 12),
array("Gold", "Metallic", 12)
),
);
$accumulated = array();
$key = "";
$callback = function($item, $index) use(&$key, &$accumulated) {
if($index != 2) {
$key .= $item;
} else {
if(!array_key_exists($key, $accumulated)) {
$accumulated[$key] = 0;
}
$accumulated[$key] += $item;
$key = "";
}
};
array_walk_recursive($products, $callback);
var_dump($accumulated);
Should be a simple case of looping over the data and storing an array of sums. This is one possibility using a hash with keys as the pairs concatenated with a separator sentinel value.
$separator = "||"; //take care to choose something that doesn't pop up in your data here
//$data = example data;
$pairs = array();
foreach ($data as $val) {
foreach ($val as $pair) {
$str = $pair[0] . $separator . $pair[1];
if (array_key_exists($str, $pairs))
$pairs[$str] += $pair[2];
else
$pairs[$str] = $pair[2];
}
}
print_r($pairs);
output:
["Black||Toscano"] => 26,
["Gold||Metallic"] => 22
The data can be easily retrieved at this point
foreach ($pairs as $str => $sum) {
$str = explode($separator, $str);
echo $str[0] . ", " . $str[1] . ": " . $sum;
}

Calculating average value for array with PHP?

My head is exploding with this. I can't seem to create a working solution.
I have a file in this format:
99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15
I want to calculate average values from third column for each id from the first column.
This seems so easy but I can't get this to work. How do you get averages for any said id from first column?
EDIT:
Some sample code I've written before:
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$howMany = count($file);
for($a = 0;$a<$howMany;$a++)
{
$row = explode("|", $file[$a]);
$id = $row[0];
$howManyAlready = count($bigTable[$id]);
$bigTable[$id][$howManyAlready] = $row[2];
}
I've added the code. So far it gets the results into an array ( with offset corresponding to its id ) But I am having trouble with how to get those results and calculate average for each id and then present it on the screen.
Something like this should definitely work..
<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
array_push($arr,#array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);
You can try doing this :
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$valuesPerID = Array();
foreach($file as $row)
{
$row_array = explode("|", $row);
$id = $row_array[0];
if(!array_key_exists($id, $valuesPerID))
{
$valuesPerID[$id] = Array();
}
$valuesPerID[$id][] = $row_array[2];
}
Now in the $valuesPerID array, you'll have all your ID as keys, and for each ID, all the values associated with the said ID. They you can easily calculate the average of these values !
You can use array mapping to assign value and id.
For example (assume that you have handled the text):
<?php
$data = array("99895|35378|0.01",
"99895|813|-0.97",
"99895|771|0.29",
"442|833|-1.06",
"442|485|-0.61",
"442|367|-0.14",
"442|478|0.77",
"442|947|-0.07",
"7977|987|0.76",
"7977|819|0.37",
"7977|819|0.36",
"7977|653|1.16",
"7977|1653|1.15");
$bucket = array();
$count = array();
foreach($data as $line) {
list($id, $what_s_this, $number) = explode("|", $line);
$count[$id]++;
$bucket[$id]+= (float)$number;
}
foreach($bucket as $id => $sum) {
echo "id:". $id. ", average". $sum / $count[$id]. "\n";
}
This should put you on the right track.
<?php
$values = array();
foreach (file('file.txt') as $line) {
list($id, $thingymabob, $value) = explode('|', $line);
if ( ! array_key_exists($id, $values)) {
$values[ $id ] = array();
}
array_push($values[ $id ], $value);
}
foreach ($values as $id => $value) {
printf(
"%d has an average of %f\n",
$id,
array_sum($value) / count($value)
);
}
Here some something I've just written.
In my example it takes it from a string.
<?php
$test1 = "";
$test2 = "";
$count1 = 0;
$count2 = 0;
$string = "99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15";
$d = explode("\n", $string);
foreach ($d as $k => $v)
{
$d2 = explode("|", $v);
if ($d2[0] == '99895'){
$count1++;
$test1 += $d2[2];
}
if ($d2[0] == '442'){
$count2++;
$test2 += $d2[2];
}
}
$result1 = $test1 / $count1;
$result2 = $test2 / $count2;
echo $result1. " <br> ". $result2;
I don't know how well this will work as I don't know if the values are set or not.
If You try below code
<?php
$file_content = array();
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$line_ex = explode("|",$line);
array_push($file_content,$line_ex);
}
} else {
// error opening the file.
}
echo "<pre>";
print_r($file_content);
echo "<pre>";
?>
then You will get below output
Array
(
[0] => Array
(
[0] => 99895
[1] => 35378
[2] => 0.01
)
[1] => Array
(
[0] => 99895
[1] => 813
[2] => -0.97
)
[2] => Array
(
[0] => 99895
[1] => 771
[2] => 0.29
)
[3] => Array
(
[0] => 442
[1] => 833
[2] => -1.06
)
[4] => Array
(
[0] => 442
[1] => 485
[2] => -0.61
)
[5] => Array
(
[0] => 442
[1] => 367
[2] => -0.14
)
[6] => Array
(
[0] => 442
[1] => 478
[2] => 0.77
)
[7] => Array
(
[0] => 442
[1] => 947
[2] => -0.07
)
[8] => Array
(
[0] => 7977
[1] => 987
[2] => 0.76
)
[9] => Array
(
[0] => 7977
[1] => 819
[2] => 0.37
)
[10] => Array
(
[0] => 7977
[1] => 819
[2] => 0.36
)
[11] => Array
(
[0] => 7977
[1] => 653
[2] => 1.16
)
[12] => Array
(
[0] => 7977
[1] => 1653
[2] => 1.15
)
)
For determining average value from third column of corresponding first column - I am researching on it. When I will be done I'll put it here.
Try this:
$filename = 'results.txt';
$result = $counter = $values = array();
$file = fopen($filename, 'r') or die("Couldn't open $filename");
while ($line = fgets($file)) {
$content = explode('|', $line);
if (empty($content[0]) or empty($content[2]))
continue;
$values[$content[0]][] = (float) $content[2];
++$counter[$content[0]];
}
foreach ($values as $key => $value) {
$result[$key] = array_sum($value) / $counter[$key];
}
fclose($file);

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

Php Array removing duplication and string conversion

hi i have output of an array as follow:
Array (
[0] => 66, 65, 64
[1] => 57
[2] => 66,23
[3] => 66
)
How can i remove duplication values and convert the collection into comma separated string? The unique output is 66,65,64,57,23. Thanks
Make use of array_unique() and array_reverse():
$array = Array (
0 => '66, 65, 64',
1 => '57',
2 => '66,23',
3 => '66',
);
$collection = array();
foreach($array as $numbers) {
$nums = explode(',', $numbers);
foreach($nums as $num) {
$collection[] = trim($num);
}
}
// unique and sort
$collection = array_unique($collection, SORT_NUMERIC);
// reverse it so that it can be descending order
$collection = array_reverse($collection);
print_r($collection);
which will output :
Array (
[0] => 66
[1] => 65
[2] => 64
[3] => 57
[4] => 23
)
you iterate through the array and add it to a final array by checking its values then implode to construct a string.
$array = Array (
0 => array(66, 65, 64),
1 => array(57),
2 => array(66,23),
3 => array( 66)
);
$final = array();
foreach ($array as $item) {
foreach ($item as $num) {
if (!in_array($num, $final)) $final[] = $num;
}
}
$str = implode(",", $final);
echo $str
well, the code is lil ugly...
$test = [
'0' => '66, 65',
'1' => '80', '66'
];
$temp = implode(',', array_map('trim', array_unique(explode(',', implode(',', $test)))));
print_r($test);
print_r($temp);
//output
Array (
[0] => 66, 65
[1] => 80
[2] => 66
)
66,65,80
Ok:
<?php
$array = array(
"66, 65, 64",
57,
"66,23",
66
);
function dosplit($a,$b) {
if (preg_match("/,/",$b)) {
$a = array_merge($a, preg_split('/\s*,\s*/', $b));
} else {
array_push($a, $b);
}
return $a;
}
$result = array_reduce($array, 'dosplit' ,array());
$array = array_unique($result);
The output is:
Array
(
[0] => 66
[1] => 65
[2] => 64
[3] => 57
[5] => 23
)
This might is useful for you:
$array = array(
"66, 65, 64 ",
"57",
"66,23",
"66",
);
echo "<pre>";
print_r($array);
//to make single line
foreach ($array as $val) {
$singleline.=$val . ",";
}
echo $singleline . "</br>";
//remove the "," end of the value
$endvlaue = rtrim($singleline, ",");
echo $endvlaue;
//make an array
$val = explode(",", $endvlaue);
echo "<pre>";
print_r($val);
echo "<pre>";
//make uniqu
$finalvalue = array_unique($val);
echo "<pre>";
//make , seperator
print_r(implode(",", $finalvalue));

How to get deep key in array php?

If a have an array:
Array
(
[1-title1] => Array
(
[0] => title = title erer
[1] => 1-title1
[2] => content = content 1
)
[2-title2] => Array
(
[0] => title = title dffgfghfdg
[1] => 2-title2
[2] => content = content 2
)
and I want to get array:
Array
(
[1-title1] => Array
(
[title] =>title erer
[1] =>title1
[content] =>content 1
)
[2-title2] => Array
(
[title] =>title dffgfghfdg
[2] => title2
[content] =>content 2
)
What should I do?
A solution without references and no implicit key names.
foreach ($array as $key => $innerArray) {
foreach ($innerArray as $innerKey => $value) {
if (false !== strpos($value, ' = ')) {
unset($array[$key][$innerKey]);
list($innerKey, $value) = explode(' = ', $value, 2);
$array[$key][$innerKey] = $value;
}
}
}
foreach($array as &$title){
$newTitle = array();
$titleName = explode(' = ', $title[0] , 2);
$newTitle['title'] = end($titleName);
$titleNum = explode('-', $title[1] , 2);
$newTitle[$titleNum[0]] = $titleNum[1];
$titleContent = explode(' = ', $title[2] , 2);
$newTitle['content'] = end($titleContent);
$title = $newTitle;
}
try this
foreach($array as $ky=>$val) {
echo $ky;
var_dump(array_keys($val));
}

Categories