I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>
Related
Why foreach loop printing only the first value from the array?
$Jdata_cate = '[{"category_id":"103","name":"Martin","parent_id":0},{"category_id":"10","name":"Juan","parent_id":0},{"category_id":"9","name":"Kasi","parent_id":0}]';
$J_Min = strtolower($Jdata_cate);
$J_MinDecoded = json_decode($J_Min, true);
$Ddata_cate = '[{"category_id":"55","name":"Abc","parent_id":0},{"category_id":"41","name":"Pedro","parent_id":0},{"category_id":"40","name":"Kasi","parent_id":0}]';
$D_Min = strtolower($Ddata_cate);
$D_MinDecoded = json_decode($D_Min, true);
$both_arrays = array_merge((array)$J_MinDecoded, (array)$D_MinDecoded);
$Delete_repeated = array_unique($both_arrays);
foreach($Delete_repeated as $y=>$y_value){
echo $y_value['name'] . '<br>';
}
try this solution:
function array_unique_multidimensional($array, $key)
{
$temp_array = array();
$i = 0;
$key_array = array();
foreach ($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$Jdata_cate = '[{"category_id":"103","name":"Martin","parent_id":0},{"category_id":"10","name":"Juan","parent_id":0},{"category_id":"9","name":"Kasi","parent_id":0}]';
$J_Min = strtolower($Jdata_cate);
$J_MinDecoded = json_decode($J_Min, true);
$Ddata_cate = '[{"category_id":"55","name":"Abc","parent_id":0},{"category_id":"41","name":"Pedro","parent_id":0},{"category_id":"40","name":"Kasi","parent_id":0}]';
$D_Min = strtolower($Ddata_cate);
$D_MinDecoded = json_decode($D_Min, true);
$both_arrays = array_merge((array)$J_MinDecoded, (array)$D_MinDecoded);
$Delete_repeated = array_unique_multidimensional($both_arrays, 'name');
foreach ($Delete_repeated as $y => $y_value) {
echo $y_value['name'] . '<br>';
}
here instead of array_unique I'm using my defined function
The problem is where you call array_unique($both_arrays) the default behavior is to compare items as strings, but they are arrays so it fails.
The solution is to add the SORT_REGULAR flag as the second parameter.
$Delete_repeated = array_unique($both_arrays, SORT_REGULAR);
I want to group in subarray the identical values while preserving the original order of each group of values.
I want this :
array('a','b','b','c','c','c','a','a');
to become :
array( array('a'),array('b','b'),array('c','c','c'),array('a','a'));
$source = array('a','b','b','c','c','c','a','a');
$tempvalue = false;
$temparr = array();
$new = array();
foreach ($source as $value) {
if ($tempvalue && $value != $tempvalue){
$new[] = $temparr;
$temparr = array();
}
$temparr[] = $value;
$tempvalue = $value;
}
$new[] = $temparr;
echo json_encode($new);
output:
[["a"],["b","b"],["c","c","c"],["a","a"]]
How can I make a two dimensional array with the following example using for loop:
$test = array ('D','D','D','D','C','C','D','D');
output should be like this:
$output = array( 0 => array('D','D','D','D'), 1 => array('D','D'));
thanks for your help.
Here is my code:
$test = array('D','D','D','D', 'C','C','D', 'D');
$output = array();
$myarray = array();
for ($i= 0; $i < count($test); $i++){
if($test[$i] == 'D'){
array_push($myarray , $test[$i]);
} else {
array_push($output,$myarray);
}
}
//OUTPUT: $output = (array( 0 => array('D','D','D','D'), 1 => array('D','D','D','D'));
this can be implemented using only one foreach loop.
<?php
$test = array ('D','C','D','D','D','D','C','C','D','D','C','D');
$temp = array();
$result = array();
foreach($test as $value){
if($value != 'D' && !empty($temp)){
array_push($result, $temp);
$temp = array();
}
else{
array_push($temp, $value);
}
}
if(!empty($temp)){
array_push($result, $temp);
}
print_r($result);
I have an array like that
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that
$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));
I achieved this array using this code
foreach($products as $val)
{
$abc[] =$val[0];
}
for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}
for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}
echo '<pre>';
print_r($arrProducts);
but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);
$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
$arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}
echo '<pre>';
print_r($arrProducts);
Another alternative would be:
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));
This will yield the same result.
Consume two array elements on each iteration:
$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
$arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0)
{
$abc[$j]['qty'] =$val[0];
$j++;
}
else
{
$abc[$j]['product_id'] =$val[0];
}
$i++;
}
I have an array for example ("1:2","5:90","7:12",1:70,"29:60") Wherein ID and Qty are separated by a ':' (colon), what I want to do is when there's a duplicate of IDs the program will add the qty and return the new set of arrays so in the example it will become ("1:72","5:90","7:12","29:60").
Ex.2
("1:2","5:90","7:12","1:70","29:60","1:5")
becomes
("1:77","5:90","7:12","29:60").
<?php
$arr = array("1:2","5:90","7:12", "1:70","29:60");
$newArr = array();
foreach($arr as $key => $value) {
list($id, $quantity) = explode(':', $value);
if(isset($newArr[$id]))
$newArr[$id] += $quantity;
else
$newArr[$id] = $quantity;
}
foreach($newArr as $key => $value) {
$newArr[$key] = "$key:$value";
}
print_r($newArr);
Simple step by step:
$arr = array("1:2","5:90","7:12","1:70","29:60");
$tmp = array();
foreach($arr as $item)
{
list($id, $value) = explode(':', $item);
if (isset($tmp[$id]))
$tmp[$id] += $value;
else
$tmp[$id] = $value;
}
$arr = array();
foreach($tmp as $id => $value)
array_push($arr, $id . ':' . $value);
var_dump($arr);
Assuming the data format is an actual array, or you can parse it into one:
$data = array("1:2","5:90","7:12","1:70","29:60","1:5");
$values = array();
foreach ($data as $value) {
list($id, $qty) = explode(':', $value);
if (isset($values[$id])) {
$values[$id] += $qty;
} else {
$values[$id] = $qty;
}
}
foreach ($values as $id => &$qty) {
$qty = "$id:$qty";
}
$values = array_values($values);
Try to do like this
$array = array("1:2","5:90","7:12","1:70","29:60","1:5");
$result = array();
$sum = array();
foreach($array as $value)
{
list($k,$v) = explode(':',$value);
$sum[$k] += $v;
$result[$k] = $k.':'.$sum[$k];
}
unset($sum);
print_r($result);