How to sum array the same value of element ?
$arr = [
['id' => 1, 'qty' => 100, 'name' => 'a'],
['id' => 1, 'qty' => 100, 'name' => 'a'],
['id' => 2, 'qty' => 100, 'name' => 'b']
];
become to :
$arr = [
['id' => 1, 'qty' => 200, 'name' => 'a'],
['id' => 2, 'qty' => 100, 'name' => 'b']
];
i was try but return
[ 1=>['qty'=>200], 2=>['qty'=>100] ]
i was try but return
for($i=0; $i<count($cok);$i++){
$item_id = $cok[$i]['id'];
$quantity = $cok[$i]['quantity'];
if (isset($new_items[$item_id])) {
$new_items[$item_id] = ['quantity' => $new_items[$item_id]['quantity'] + $quantity];
} else {
$new_items[$item_id] = ['quantity' => $quantity];
}
}
Simple as pie (:
<?php
$arr = array(
array('id' => 1, 'qty' => 100, 'name' => 'a'),
array('id' => 1, 'qty' => 100, 'name' => 'a'),
array('id' => 2, 'qty' => 100, 'name' => 'b')
);
$new_arr = array();
foreach($arr AS $item) {
if(isset($new_arr[$item['id']])) {
$new_arr[$item['id']]['qty'] += $item['qty'];
continue;
}
$new_arr[$item['id']] = $item;
}
$arr = array_values($new_arr);
var_dump($arr);
Dive into my viper
And inplace snippet, returns exactly you need:
<?
$arr = array(
array('id' => 1, 'qty' => 100, 'name' => 'a'),
array('id' => 1, 'qty' => 100, 'name' => 'a'),
array('id' => 2, 'qty' => 100, 'name' => 'b')
);
$ids = array();
foreach ($arr as $i => $subarray) {
if (!($remove_from_array = array_key_exists($subarray['id'], $ids))) {
$ids[$subarray['id']] = 0;
}
$ids[$subarray['id']] += $subarray['qty'];
if ($remove_from_array) {
unset($arr[$i]);
}
}
foreach ($arr as &$subarray) {
$subarray['qty'] = $ids[$subarray['id']];
}
print_r($arr);
Related
I have 2 associative arrays.
$a1 = array(
'blue' =>
array('id' => 2365,
'level' => 1,
'name' => 'blue'),
'black' =>
array('id' => 478,
'level' => 1,
'name' => 'black'),
'green' =>
array('id' => 698,
'level' => 1,
'name' => 'green'),
'red' =>
array('id' => 169,
'level' => 1,
'name' => 'red')
$a2= array(
'green' =>
array('id' => 452,
'level' => 1,
'name' => 'green'),
'black' =>
array('id' => 124,
'level' => 1,
'name' => 'black'),
'red' =>
array('id' => 124,
'level' => 1,
'name' => 'red'),
'blue' =>
array('id' => 145,
'level' => 1,
'name' => 'blue')
);
I want to sort my second array in the first array key order. That means I want to sorry my array of blue, black, green, red.
My desired result like:
$a2= array(
'blue' =>
array('id' => 145,
'level' => 1,
'name' => 'blue'),
'black' =>
array('id' => 124,
'level' => 1,
'name' => 'black'),
'green' =>
array('id' => 452,
'level' => 1,
'name' => 'green'),
'red' =>
array('id' => 124,
'level' => 1,
'name' => 'red'),
);
For this I am using the code :
uasort($a2, function($a, $b) use ($a1) { return array_search($a['name'], $a1) - array_search($b['name'], $a1); }
But I didn't get my desired result.
Also I tried with this:
uksort($a2, function($key1, $key2) use ($a1) {
return (array_search($key1, $a1) - array_search($key2, $a1));
});
Another method: But again, I didn't get my desired result.
$price = array();
foreach ($a2 as $key => $row) {
$price[$key] = $row['name'];
}
array_multisort($price, SORT_DESC, $a1);
I just use the following concept:
$arr2ordered = array() ;
foreach (array_keys($a1) as $key) {
$arr2ordered[$key] = $a2[$key] ;
}
After that, I got my desired result.
I guess my brain starts to slow down, but I want to get a recursive array of my results from this table :
|id|int(11)|
|name|varchar(150)|
|type|tinyint(4)|
|id_parent|mediumint(9)|
|1|Marque forte|1|0|
|2|Communication|2|1|
|3|Respect du CI|0|2|
|4|Stratégie digitale|0|2
|5|Expérience de marque|2|1|
|6|Gastronomie|0|5|
I want an array like :
array('id' => array('name' => $name, 'childs' => array( ... ), 'id' => ...)
I just want to order my dataset in one array.
I tried this so far :
// returns array of objects - codeigniter result
$dbResult = $this->db->get_where('table')->result();
// will contains the array
$this->data['tree'] = array();
$this->getRecursive(0, 0, $dbResult);
....
private function getRecursive($parent, $niveau, $result)
{
foreach ($result AS $row)
{
if ($parent == $row->id_parent)
{
$this->data['tree'][] = array($row->name => $this->getRecursive($row->id, ($niveau + 1), $result));
}
}
}
Which gives me weird result ...
Please try this. I have used the $source array for testing. Since I did not get my result set from an actual database, you will have to make some changes in order to adjust it with your code (eg. change $row['id_parent'] to $row->id_parent and so on). However, conceptually it should work.
<?php
$source = [
['name' => 'A', 'id' => 1, 'id_parent' => 0],
['name' => 'B', 'id' => 2, 'id_parent' => 1],
['name' => 'C', 'id' => 3, 'id_parent' => 1],
['name' => 'D', 'id' => 4, 'id_parent' => 2],
['name' => 'E', 'id' => 5, 'id_parent' => 3],
['name' => 'F', 'id' => 5, 'id_parent' => 0],
];
function getRecursive($source, $parent) {
$result = [];
foreach ($source as $row) {
if ($parent == $row['id_parent']) {
$result[] = [
'id' => $row['id'],
'name' => $row['name'],
'childs' => getRecursive($source, $row['id'] )
];
}
}
return $result;
}
print_r(getRecursive($source, 0));
You don't need a recursion here - the following should do the job
$arrTreeById = [];
//$arrData = $this->db->get_where('table')->result_array();
$arrData = [
[
'id' => 1,
'name' => 'Marque forte',
'type' => 2,
'id_parent' => 0
],
[
'id' => 2,
'name' => 'Communication',
'type' => 2,
'id_parent' => 1
],
[
'id' => 3,
'name' => 'Respect du CI',
'type' => 0,
'id_parent' => 2
],
[
'id' => 4,
'name' => 'Stratégie digitale',
'type' => 0,
'id_parent' => 2
],
[
'id' => 5,
'name' => 'Expérience de marque',
'type' => 2,
'id_parent' => 1
],
[
'id' => 6,
'name' => 'Gastronomie',
'type' => 0,
'id_parent' => 5
],
];
foreach($arrData AS $arrItem)
{
$arrTreeById[$arrItem['id']] = $arrItem;
}
foreach($arrTreeById AS &$arrItem)
{
if (isset($arrTreeById[$arrItem['id_parent']]))
{
$arrTreeById[$arrItem['id_parent']]['arrChilds'][] = &$arrItem;
}
if ($arrItem['id_parent'] == 0) $intStartingKey = $arrItem['id'];
}
print_r($arrTreeById[$intStartingKey]);
So I have this array:
$arr = array(
array('category' => 'box', 'product' => 'gloves', 'quantity' => 45, 'price' => 30),
array('category' => 'karate', 'product' => 'gloves', 'quantity' => 55, 'price' => 25),
array('category' => 'mma', 'product' => 'gloves', 'quantity' => 55, 'price' => 35),
array('category' => 'mma', 'product' => 'shorts', 'quantity' => 120, 'price' => 50),
array('category' => 'karate', 'product' => 'belt', 'quantity' => 25, 'price' => 55),
array('category' => 'judo', 'product' => 'costume', 'quantity' => 30, 'price' => 90),
array('category' => 'karate', 'product' => 'belt', 'quantity' => 25, 'price' => 90)
);
I need to find out the average price for every product type, for e.g:
(box gloves + karate gloves + mma gloves) / 3 = (30+25+35)/3 = 30.
This is my code right now that output an array with the sum for every product type:
$tmp = array();
foreach($arr as $key => $value) {
$tmp[$arr[$key]['product']] = isset($tmp[$arr[$key]['product']]) ? $tmp[$arr[$key]['produs']]: 0;
$tmp[$arr[$key]['product']] = $tmp[$arr[$key]['product']] + $arr[$key]['price'];
}
The output:
[gloves] => 90
[shorts] => 50
[costume] => 90
[belt] => 145
How can I found out the count for every product type?
For example for gloves it will be 90/3, the "3" number I don't know how to obtain it.
Here is an example without arrray functions:
$arr = array(
array('category' => 'box', 'product' => 'gloves', 'quantity' => 45, 'price' => 30),
array('category' => 'karate', 'product' => 'gloves', 'quantity' => 55, 'price' => 25),
array('category' => 'mma', 'product' => 'gloves', 'quantity' => 55, 'price' => 35),
array('category' => 'mma', 'product' => 'shorts', 'quantity' => 120, 'price' => 50),
array('category' => 'karate', 'product' => 'belt', 'quantity' => 25, 'price' => 55),
array('category' => 'judo', 'product' => 'costume', 'quantity' => 30, 'price' => 90),
array('category' => 'karate', 'product' => 'belt', 'quantity' => 25, 'price' => 90)
);
$tmp = array();
foreach ($arr as $value) {
if (isset($tmp[$value['product']])) {
$tmp[$value['product']]['total'] += $value['price'];
$tmp[$value['product']]['price'] += 1;
} else {
$tmp[$value['product']]['total'] = $value['price'];
$tmp[$value['product']]['price'] = 1;
}
}
foreach ($tmp as $key => $value) {
$tmp[$key] = $value['total'] / $value['price'];
}
$tmp values:
[
'gloves' => (int) 30,
'shorts' => (int) 50,
'belt' => (float) 72.5,
'costume' => (int) 90
]
Instead of summing the prices as you go, just add them to an array.
foreach ($arr as $item) {
$products[$item['product']][] = $item['price'];
}
Then you can calculate the average of the resulting groups.
$products = array_map(function($product){
return array_sum($product) / count($product);
}, $products);
var_dump($products);
The solution using array_reduce and array_map functions:
$result = array_map(function($v){
$c = count($v);
return ($c > 1)? array_sum($v)/$c : $v[0];
}, array_reduce($arr, function($r, $a){
$r[$a['product']][] = $a['price']; // accumulating prices for each `product`
return $r;
}, []));
print_r($result);
The output:
Array
(
[gloves] => 30
[shorts] => 50
[belt] => 72.5
[costume] => 90
)
I have an array like this:
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'A', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'A', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'A', 'parent_id' => 2],
4 => ['id'=> 5, 'name' => 'A', 'parent_id' => 4]
How can I iterate over this to create a nested array where items are inside of each other based on their parent_id?
Result to look like something like this:
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null, 'children' => [['id'=> 2, 'name' => 'A', 'parent_id' => 1, 'children' => [['id'=> 3, 'name' => 'A', 'parent_id' => 2], ['id'=> 4, 'name' => 'A', 'parent_id' => 2, 'children' => [['id'=> 4, 'name' => 'A', 'parent_id' => 4]]]]]]]
Use recursive function :
$arr = array(
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'A', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'A', 'parent_id' => 1],
3 => ['id'=> 4, 'name' => 'A', 'parent_id' => 2],
);
function add_childs(array $elements, $parentId = null) {
$parent = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
echo "in if".$element['id']."<br>";
$children = add_childs($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$parent[] = $element;
}
}
return $parent;
}
$result = add_childs($arr);
print_r($result);
example : https://eval.in/745350
EDIT : I understood the question other way (parent attached to child)...
You have to iterate over users to look for every parent/child pairing.
<?php
$users = [
0 => ['id'=> 1, 'name' => 'A', 'parent_id' => null],
1 => ['id'=> 2, 'name' => 'B', 'parent_id' => 1],
2 => ['id'=> 3, 'name' => 'C', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'D', 'parent_id' => 2],
3 => ['id'=> 4, 'name' => 'E', 'parent_id' => 4]
];
foreach($users as $user){
foreach($users as &$parent){
if($user['parent_id'] == $parent['id']){
$parent['children'][] = $user;
}
}
}
var_dump($users);
?>
I need to sort an array that can look like this:
$array[4][0] = array('id' => 1, 'value' => 2);
$array[3][2] = array('id' => 0, 'value' => 3);
$array[4][1] = array('id' => 1, 'value' => 0);
$array[1][3] = array('id' => 2, 'value' => 1);
$array[1][1] = array('id' => 3, 'value' => 0);
$array[3][0] = array('id' => 2, 'value' => 1);
$array[3][1] = array('id' => 1, 'value' => 0);
$array[1][2] = array('id' => 3, 'value' => 2);
$array[1][0] = array('id' => 2, 'value' => 1);
$array[2][1] = array('id' => 0, 'value' => 2);
$array[2][4] = array('id' => 3, 'value' => 1);
But needs to be sorted and returned as this:
$array[1][0] = array('id' => 2, 'value' => 1);
$array[1][1] = array('id' => 3, 'value' => 0);
$array[1][2] = array('id' => 3, 'value' => 2);
$array[1][3] = array('id' => 2, 'value' => 1);
$array[2][1] = array('id' => 0, 'value' => 2);
$array[2][4] = array('id' => 3, 'value' => 1);
$array[3][0] = array('id' => 2, 'value' => 1);
$array[3][1] = array('id' => 1, 'value' => 0);
$array[3][2] = array('id' => 0, 'value' => 3);
$array[4][0] = array('id' => 1, 'value' => 2);
$array[4][1] = array('id' => 1, 'value' => 0);
Can anyone help me? It needs to sort both indexes of the array from lowest to highest index value. Sounds simple enough, but I'm having the hardest time trying to figure this out, while still keeping the values intact.
Please help someone...
A quick'n'dirty solution might look something like:
// Sort the outer array
ksort($array);
// Sort each inner array
foreach($array as &$innerArray)
{
ksort($innerArray);
}
You want to sort it by key then, and not by values: http://se.php.net/manual/en/function.ksort.php or http://se.php.net/manual/en/function.uksort.php
Edit,
Example;
function sorter(array &$multidimensional) {
foreach ($multidimensional as &$current) {
if (is_array($current))
sorter($current);
}
ksort($multidimensional);
}
Something like this should do it:
function ksort_recursive(&$arr) {
foreach($arr as $key => &$value) {
if(is_array($value)) {
ksort_recursive($value);
}
} unset($value);
ksort($arr);
}
ksort_recursive($array);