Merge array key values - php

I have this array structure that contains ids of one tournament players:
array (
0 =>
array (
0 =>
array (
'player' => 7,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 1,
),
),
1 =>
array (
0 =>
array (
'player' => 10,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 1,
),
),
),
This array have some duplicates ('player'). I would to generate an array that not contains duplicate of players, and the result will be sum of each goal by player, such as:
array(
0 =>
array (
'player' => 7,
'gol' => 1,
),
1 =>
array (
'player' => 9,
'gol' => 2,
),
2 =>
array (
'player' => 10,
'gol' => 1,
),
),
This is my code:
if ($query->have_posts()) {
$players = [];
while ($query->have_posts()) {
$query->the_post();
if (have_rows('field_name', $id)):
while (have_rows('field_name', $id)) : the_row();
$tmp = [];
$player = get_sub_field('player_name', $id);
$tmp['player'] = $player['ID'];
$tmp['gol'] = get_sub_field('player_goal', $id);
array_push($players, $tmp);
}
}

$games = array (
array(array("player"=>7,"gol"=>1),array("player"=>9,"gol"=>1)),
array(array("player"=>10,"gol"=>1),array("player"=>9,"gol"=>1)),
); //Input array
$player = array();
foreach($games as $game) foreach($game as $gol) //For game and gol
#$player[$gol["player"]]+=$gol["gol"]; //sum gols
arsort($player); //sort by value
print_r($player);
Output
Array
(
[9] => 2
[10] => 1
[7] => 1
)

Naive way (I took the sample from FAEWZX answer ):
$games = array (
array(array("player"=>7,"gol"=>1),array("player"=>9,"gol"=>1)),
array(array("player"=>10,"gol"=>1),array("player"=>9,"gol"=>1)),
);
$player = array();
foreach($games as $game)
{
foreach($game as $gol)
{
if(in_array($gol['player'], array_column($player, 'player')))
{
foreach($player as $key => $value)
{
if($value['player'] == $gol['player'])
{
$player[$key]['gol'] += $gol['gol'];
break;
}
}
}
else
{
$player[] = $gol;
}
}
}
print_r($player);
Output :
Array
(
[0] => Array
(
[player] => 7
[gol] => 1
)
[1] => Array
(
[player] => 9
[gol] => 2
)
[2] => Array
(
[player] => 10
[gol] => 1
)
)

Related

In for loop how to check current array value with all previous array in php

In for loop how to check current value with each and every previous value using php
my array:
In array list [prolabelpos] =>0 having three times, how to execute a [prolabelpos] =>0 only one time in for loop . how to check current array with all previous value and [prolabelpos] =>0 execute once in the for loop
Array (
[0] => Array ( [productlabel_id] => 6 [prolabelpos] => 0 )
[1] => Array ( [productlabel_id] => 5 [prolabelpos] => 6 )
[2] => Array ( [productlabel_id] => 4 [prolabelpos] => 0 )
[3] => Array ( [productlabel_id] => 3 [prolabelpos] => 5 )
[4] => Array ( [productlabel_id] => 2 [prolabelpos] => 0 )
)
my code:
<?php
$prev = null;
foreach ($result as $key => $value) {
$label_position = $value['prolabelpos'];
if ($prev != $label_position) {
echo "my code";
}
$prev = $label_position;
}
You can approach this in foreach OR array_map
$arr =
Array (
'0' => Array ( 'productlabel_id' => 6, 'prolabelpos' => 0 ),
'1' => Array ( 'productlabel_id' => 5, 'prolabelpos' => 6 ),
'2' => Array ( 'productlabel_id' => 4, 'prolabelpos' => 0 ),
'3' => Array ( 'productlabel_id' => 3, 'prolabelpos' => 5 ),
'4' => Array ( 'productlabel_id' => 2 ,'prolabelpos' => 0 )
);
$traversed = array();
foreach($arr as $value){
if(in_array($value['prolabelpos'], $traversed)){
//This has been traversed before
}else{
/* Apply your Logic */
$traversed[] = $value['prolabelpos'];
}
}
Using array_map
$arr = Array (
'0' => Array ( 'productlabel_id' => 6, 'prolabelpos' => 0 ),
'1' => Array ( 'productlabel_id' => 5, 'prolabelpos' => 6 ),
'2' => Array ( 'productlabel_id' => 4, 'prolabelpos' => 0 ),
'3' => Array ( 'productlabel_id' => 3, 'prolabelpos' => 5 ),
'4' => Array ( 'productlabel_id' => 2 ,'prolabelpos' => 0 )
);
$traversed = array();
array_map(function($v) use (&$traversed){
if(in_array($v['prolabelpos'], $traversed)){
//This has been traversed before
}else{
/* Apply your Logic */
$traversed[] = $v['prolabelpos'];
}
}, $arr);

How to get Php multidimensional array same key’s same value’s related total in new array?

Php multidimensional array same key’s same value’s related total in
new array. I have an array of following mentioned. i need new array
as total qty of same item_id. anyone can help would be appreciate.
My Original Array is as following
Array
(
[a] => Array
(
[item] => Array
(
[item_id] => 1
)
[qty] => 0
),
[b] => Array
(
[item] => Array
(
[item_id] => 2
)
[qty] => 35
),
[c] => Array
(
[item] => Array
(
[item_id] => 2
)
[qty] => 15
),
[e] => Array
(
[item] => Array
(
[item_id] => 3
)
[qty] => 20
),
);
I want array Output like following :
Array(
[0] => Array (
[item_id] => 1,
[item_total_qty] => 0,
)
[1] => Array (
[item_id] => 2,
[item_total_qty] => 50,
)
[2] => Array (
[item_id] => 3,
[item_total_qty] => 20,
)
);
Hope it help
$arrays = array(
'a' => array(
'item' => array(
'item_id' => 1
),
'qty' => 0
),
'b' => array(
'item' => array(
'item_id' => 2
),
'qty' => 35
),
'c' => array(
'item' => array(
'item_id' => 2
),
'qty' => 15
),
'd' => array(
'item' => array(
'item_id' => 3
),
'qty' => 20
)
);
$result = array();
foreach ($arrays as $key => $array) {
if (is_array($result) && !empty($result)) {
foreach ($result as $key => $r) {
if ($r['item_id'] == $array['item']['item_id']) {
$result[$key]['item_total_qty'] += $array['qty'];
continue 2;
}
}
$result[] = array(
'item_id' => $array['item']['item_id'],
'item_total_qty' => $array['qty']);
} else {
$result[] = array(
'item_id' => $array['item']['item_id'],
'item_total_qty' => $array['qty']);
}
}
Simple foreach on your original table:
$sorted = array();
foreach ($original as $item) {
$id = $item['item']['item_id'];
$sorted[$id]['item_total_qty'] = $sorted[$id] ? $sorted[$id] + $item['qty'] : item['qty'];
$sorted[$id]['item_id'] = $id;
}
$sorted = array_values($sorted);

PHP : Concatenate arrays with condition

I'm trying to read a session variable, create arrays and concatenate them :
Session variable sample:
Array
(
[0] => Array
(
[idArticle] => 224
[ntypeArticle] => 1
)
[1] => Array
(
[idArticle] => 556
[ntypeArticle] => 2
)
[2] => Array
(
[idArticle] => 312
[ntypeArticle] => 1
)
)
I need to read this arrays one by one and create arrays by "ntypeArticle".
If ntypeArticle=1, create array1
If ntypeArticle=2, create array2
My code :
$type1 = array();
$type2= array();
$typeAll = array();
foreach($_SESSION['cart'] as $item)
{
if ($item['ntypeArticle'] == 1) {
$type1= array ( "Type" => '1', );
} else {
$type2= array ( "Type" => '2', );
}
array_push($typeAll , $type1 , $type2);
}
But this creates empty arrays.
Wanted output :
Array
(
[0] => Array
(
[type] => 1
)
[1] => Array
(
[type] => 2
)
[2] => Array
(
[type] => 1
)
)
All you need is this simple thing:
$out = [];
foreach($_SESSION['cart'] as $k => $item)
{
$out[$k] = ['Type' => $item['ntypeArticle']];
}
Now if you output $out variable you get what you need.
Try This
$newOp1 = array()
$newOp2 = array()
foreach($_SESSION['cart'] as $item){
if($item["ntypeArticle"] == 1){
$newOp1[]['type'] = $item["ntypeArticle"]
}else{
$newOp2[]['type'] = $item["ntypeArticle"]
}
}
print_r($newOp1);
print_r($newOp2);
Basing on information you provided, all you want to do is to extract nTypeArticle as type element. That's all.
//array from your example
$inputArray = array(
array(
'idArticle' => 224,
'nTypeArticle' => 1
),
array(
'idArticle' => 556,
'nTypeArticle' => 2
),
array(
'idArticle' => 312,
'nTypeArticle' => 1
),
);
$outputArray = array_map(function($inputElement) {
return array('type' => $inputElement['nTypeArticle']);
}, $inputArray);
var_dump($outputArray);
//Output (the same as yours):
//array (size=3)
// 0 =>
// array (size=1)
// 'type' => int 1
// 1 =>
// array (size=1)
// 'type' => int 2
// 2 =>
// array (size=1)
// 'type' => int 1
$output = new array();
$input = array(
array(
"idArticle" => 224,
"nTypeArticle" => 1
),
array(
"idArticle" => 556,
"nTypeArticle" => 2
),
array(
"idArticle" => 312,
"nTypeArticle" => 1
)
);
foreach($input as $article) {
array_push($output, new array("type"=>$article["nTypeArticle"]));
}
print_r($output);
This gives you the thing you asked for.
(Code has been not tested)

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

Unset an multidimensional array by key

$series = array();
while($row = mysql_fetch_assoc($result)) {
$series[$row["data_id"]][] = $row;
}
The output from a print_r on $series yields for two example series:
Array (
[1] => Array ( [0] => Array ( [id] => 1 [data_id] => 1 [time_id] => 1
[data] => 1 ) [1] => Array ( [id] => 2 [data_id] => 1 [time_id] => 2
[data] => 3 ) )
[2] => Array ( [0] => Array ( [id] => 6 [data_id] => 2 [time_id] => 1
[data] => 7 ) [1] => Array ( [id] => 7 [data_id] => 2 [time_id] => 2
[data] => 4 ) )
My question: how do I unset the multidimensional array so it contains only [data] and none of the other keys? I still want $series to contain [1] and [2] but I do not want the respective sub-arrays to contain any other keys other than [data].
In fact, since I am reducing the subarrays to contain a single key, I would really like to get rid of the subarrays altogether so that I have two arrays:
$series[1] = array(1,3) and
$series[2] = array(7,4)
Try this :
$series = array();
while($row = mysql_fetch_assoc($result)) {
$series[$row["data_id"]][] = $row['data'];
}
I think you can loop in your array and build a new one keeping only data details
$array = array ('1' => array ( '0' => array ( 'id' => 1, 'data_id' => 1, 'time_id' => 1, 'data' => 1 ), '1' => array ( 'id' => 2, 'data_id' => 1, 'time_id' => 2, 'data' => 3 ), ),
'2' => array ( '0' => array ( 'id' => 6, 'data_id' => 2, 'time_id' => 1, 'data' => 7 ), '1' => array ( 'id' => 7, 'data_id' => 2, 'time_id' => 2, 'data' => 4 ) ));
$i= 0;
$n= 0;
$series = array();
foreach($array as $dato)
{
$series[$i] = array();
foreach($dato as $data)
{
foreach($data as $key => $value)
{
if($key == 'data')
{
$series[$i][$n] = $value;
$n++;
}
}
}
$n = 0;
$i++;
}
var_dump($series);
This will output
array (size=2)
0 =>
array (size=2)
0 => int 1
1 => int 3
1 =>
array (size=2)
0 => int 7
1 => int 4
Live demo

Categories