php foreach me crazy for concat key with value - php

here is my $bob array :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
[o] => Array
(
[0] => 1
[1] => 4
)
)
And i need to output in:
n-1
m-1 , m-2
l-1 , l-4 , l-64
o-1 , o-4
I tryed some
foreach ($bob as $value) {
foreach ($value as &res)
$value = $bob . "-" . $res;
}
}
I guess its pity but i'm php newbe..
All help will welcome,
Jess

You're miss curly bracket after foreach, and missprint with &res -> $res try use foreach with $key
Try this
<?php
$bob = [
'n' => [0 => 1],
'm' => [0 => 1, 1 => 2],
'l' => [0 => 1, 1 => 4, 2 => 64],
'o' => [1 => 1, 1 => 4],
];
foreach ($bob as $key => $value) {
foreach ($value as $res) {
echo $key . "-" . $res . PHP_EOL;
}
}
This output for me
php test.php
n-1
m-1
m-2
l-1
l-4
l-64
o-4

foreach ($bob as $key => $value) {
foreach ($value as $res){
echo $key . "-" . $res ." ";
}
}
The foreach ($bob as $key => $value) syntax gives you each key for each value. You can then loop over the $value array to get the numbers you need.

Try this:
it will give you exact output with , and new line
Live demo : https://eval.in/87738
$arr =array
(
'n' => array
(
0 => 1
),
'm' => array
(
0 => 1,
1 => 2
),
'l' => array
(
0 => 1
),
'0' => array
(
0 => 1,
1 => 2,
2 => 64,
3 => 120,
)
);
$output = '';
foreach($arr as $k1 =>$v1){
$out = ' ';
foreach($arr[$k1] as $k => $v){
$out .= $k1.'-'.$v.',';
}
$output .= rtrim($out,',').'<br/>';
}
echo $output;
Output:
n-1 m-1,m-2 l-1 0-1,0-2,0-64,0-120

try $res in place of &res in following line:
foreach ($value as &res)

Can you try this,
foreach ($bob as $key=>$value) {
foreach ($value as $res){
echo $value = $key . "-" . $res."<br/>";
}
}

Related

PHP group array by date with interval

I have this array
Array
(
[0] => Array
(
[date] => 2020-10-07 10:49:48
[content] => 1
)
[1] => Array
(
[date] => 2020-10-08 13:49:48
[content] => 2
)
[2] => Array
(
[date] => 2020-10-08 13:50:03
[content] => 3
)
)
I want to get:
Array
(
[0] => Array
(
[date] => 2020-10-07 10:49:48
[content] => 1
)
[1] => Array
(
[date] => 2020-10-08 13:50:03
[content] => 2, 3
)
)
Like you see, if date between elements is less than hour (for example), content of both elements should be grouped with the greater date value. I just don't understand how to do it properly
I got this, but idk why i have extra element in array
foreach ($result as $key => $value) {
foreach ($result as $key2 => $value2) {
if (abs(strtotime($value['date_added']) - strtotime($value2['date_added'])) <= 3600 && $key != $key2) {
$result[$key]['content'] = $value['content'] . ',' . $value2['content'];
unset($result[$key2]);
}
}
$merged_array[] = $result[$key];
}
It is not clearly described which time differences should be used. The solution here always calculates the time differences to the highest date of the group.
The array will be sorted in descending order of the date. The highest date is set as $groupDate.
A new $result array is created with a foreach loop.
If the date difference to $groupDate is less than $intervalHour, then 'content' is accumulated. In the other case a new $groupDate is set. At the end the result array is sorted again according to increasing date.
$data = [
['date' => '2020-10-07 10:49:48', 'content' => 1],
['date' => '2020-10-08 13:49:48', 'content' => 2],
['date' => '2020-10-08 13:50:03', 'content' => 3],
['date' => '2020-10-08 14:50:04', 'content' => 4],
];
$intervalHour = 1.0;
usort($data,function($a,$b){return $b['date'] <=> $a['date'];});
$groupDate = date_create($data[0]['date']);
$content = $data[0]['content'];
$result = [$data[0]];
$k = 0;
foreach($data as $i => $row){
if($i == 0) continue;
$diff = date_create($row['date'])->diff($groupDate);
$diffHour = $diff->days * 24 + $diff->h + $diff->i/60 + $diff->s/3600;
if($diffHour < $intervalHour) {
$content = $row['content'].','.$content;
}
else {
++$k;
$groupDate = date_create($row['date']);
$result[$k]['date'] = $groupDate->format('Y-m-d H:i:s');
$content = $row['content'];
}
$result[$k]['content'] = $content;
}
usort($result,function($a,$b){return $a['date'] <=> $b['date'];});
echo '<pre>',var_export($result);
Output with $intervalHour = 1.0
array (
0 =>
array (
'date' => '2020-10-07 10:49:48',
'content' => 1,
),
1 =>
array (
'date' => '2020-10-08 13:50:03',
'content' => '2,3',
),
2 =>
array (
'date' => '2020-10-08 14:50:04',
'content' => 4,
),
)
Output with $intervalHour = 2.0
array (
0 =>
array (
'date' => '2020-10-07 10:49:48',
'content' => 1,
),
1 =>
array (
'date' => '2020-10-08 14:50:04',
'content' => '2,3,4',
),
)
The problem is that your unset command does not work. When you use a foreach on an array, a copy of that array will be created and iterated. If you want to iterate over an instance that you can change on the fly, you would need to pass an iterable object.
As an example, the following would output 12, despite the unset:
$x = [1, 2];
foreach ($x as $key => $value) {
echo $value;
unset($x[1]);
}
I think best approach is using OOP. But if you want to work only with forloops and arrays, it could be done like this:
$usedKeys = [];
$dateContent =[];
foreach ($result as $key => $value) {
if (in_array($key, $usedKeys)) {
continue;
}
$usedKeys[] = $key;
$dateContent[$key]['content'] = [$value['content']];
foreach ($result as $key2 => $value2) {
if (in_array($key2, $usedKeys)) {
continue;
}
if (abs(strtotime($value['date']) - strtotime($value2['date'])) <= 3600 && $key != $key2) {
$dateContent[$key]['content'][] = $value2['content'];
$usedKeys[] = $key2;
}
}
}
$dateContent = array_map(function ($value) {
return implode(',', $value['content']);
}, $dateContent);

Simplify Array Duplicate Element in Array PHP

How can we find the count of duplicate elements in a multidimensional array,
I have an array like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 8
)
[3] => Array
(
[btel] => 10
)
)
Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?
just like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 18
)
)
So far, i've tried this way, but it didn't help me. My array is store in $test
$test = [sample array]
$count = array();
foreach ($test as $key => $value) {
foreach ($value as $k => $val) {
if (isset($count[$val])) {
++$count[$val];
} else {
$count[$value] = 1;
}
}
}
print_r($count);
<?php
$array = [
"0" => ["brti" => 29],
"1" => ["voda" => 6],
"2" => ["btel" => 8],
"3" => ["btel" => 10],
];
$final = array();
array_walk_recursive($array, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
print_r($final);
});
check demo
You can do it in very simple way,
$test = [];
foreach ($array as $value)
{
foreach ($value as $k => $v)
{
// $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
$test[$k] = (empty($test[$k]) ? 0: $test[$k]); // below php 7
$test[$k] += $v;
}
}
print_r($test);
Output:
Array
(
[brti] => 29
[voda] => 6
[btel] => 18
)
Working demo.

Sum like values in Multi-Dimensional array php

I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)

How to sum the values of an associative array?

How can I add the array elements by key? Thanks in advance!
Please find the code snippet below
(
[2] => Array
(
[addition_price] => Array
(
[0] => 0
[1] => 40
[2] => 40
)
)
[3] => Array
(
[addition_price] => Array
(
[0] => 100
)
)
)
Desired result:
[2] = 0 + 40 + 40 = 80
[3] = 100
you should try this:
$array = [
0 => [
"addition_price" => [
0,
40,
40
]
],
1 => [
"addition_price" => [
100
]
],
];
foreach ($array as $key=>$value) {
if(!empty($value['addition_price']) && is_array($value['addition_price'])){
echo $key. " => " .array_sum($value['addition_price']). "<br>";
}
}
try this way, i hope it works:
foreach($array as $key => $value){
$sum = 0;
foreach($value['addition_price'] as $v){
$sum += $v;
}
$array[$key] = $sum;
}
Use array_sum for summing up, and array_map to do that for every item in the array
$result = array_map(
function($a) { return array_sum($a['addition_price']); },
$input
);

array_count_values of a multi dimensional array?

I have searched this question a lot. But I could not find a proper solution anywhere. Just like you do an array_count_values() for a single dimensional array, what do you do for a multi dimensional array if you want similar type of a solution?
For example-
Array
(
[0] => Array
(
[07/11] => 134
)
[1] => Array
(
[07/11] => 134
)
[2] => Array
(
[07/11] => 145
)
[3] => Array
(
[07/11] => 145
)
[4] => Array
(
[07/12] => 134
)
[5] => Array
(
[07/12] => 99
)
)
The output that I want is-
Date: 07/11, ID: 134, Count: 2
Date: 07/11, ID: 145, Count: 2
Date: 07/12, ID: 135, Count: 1
Date: 07/12, ID: 99, Count: 1
How do I do this?
Using the variable $arr for your array, you could do this:
$out = array();
foreach ($arr as $key => $value){
foreach ($value as $key2 => $value2){
$index = $key2.'-'.$value2;
if (array_key_exists($index, $out)){
$out[$index]++;
} else {
$out[$index] = 1;
}
}
}
var_dump($out);
Output:
Array
(
[07/11-134] => 2
[07/11-145] => 2
[07/12-134] => 1
[07/12-99] => 1
)
Here's another version that produces it as a multidimensional array:
$out = array();
foreach ($arr as $key => $value){
foreach ($value as $key2 => $value2){
if (array_key_exists($key2, $out) && array_key_exists($value2, $out[$key2])){
$out[$key2][$value2]++;
} else {
$out[$key2][$value2] = 1;
}
}
}
Output:
Array
(
[07/11] => Array
(
[134] => 2
[145] => 2
)
[07/12] => Array
(
[134] => 1
[99] => 1
)
)
<?php
$array = array(array('07/11' => '134'), array('07/11' => '134'), array('07/12' => '145'));
$count = array();
foreach ($array as $val) {
foreach ($val as $key => $subval) {
$count[$key]++;
}
}
print_r($count);
In your place I would have altered the structure of the data array. In your case:
Array(
[07/11] => Array
(
[0] => 134,
[1] => 134,
[2] => 145,
[3] => 145,
...
)
)
Smart way, We know that array_count_values(): Counts all the values of an array
Just like you do an array_count_values() for a single dimensional array, what do you do for a multi dimensional array.
We do it by turning it to one single dimensional array, then we call our funciton
$input = array(
array('07/11' => '134'),
array('07/11' => '134'),
array('07/11' => '145'),
array('07/11' => '145'),
array('07/12' => '134'),
array('07/12' => '99')
);
$output = [];
foreach ($input as $inner){
foreach ($inner as $key => $value){
$output[] = "Date: $key, ID: $value, Count:";
}
}
OUTPUT: as you expect
foreach(array_count_values($output) as $key => $value) {
echo "$key $value<br>";
}
/*Date: 07/11, ID: 134, Count: 2
Date: 07/11, ID: 145, Count: 2
Date: 07/12, ID: 135, Count: 1
Date: 07/12, ID: 99, Count: 1*/

Categories