This question already has answers here:
How to GROUP BY and SUM PHP Array? [duplicate]
(2 answers)
Closed 9 months ago.
i have bellow array
Array
(
[0] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120280
)
[1] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120281
)
[2] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120281
)
[3] => stdClass Object
(
[gross_weight] => 20.500
[net_weight] => 10.500
[product_id] => 1120280
)
)
i want loop through this records and get the sum of gross_weight and net_weight group by product_id
i tried bellow code but not able to continue from here get the out put
foreach ($my_array as $my_array_data) {
$mark_product_id = $my_array_data->product_id;
$gross_weight_mt = $mrkgdata->gross_weight_mt;
$net_weight_mt = $mrkgdata->net_weight_mt;
}
my desired out put is to get the gross_weight and net_weight for each product id in new array.
Array
(
[0] => stdClass Object
(
[gross_weight] => 41.000
[net_weight] => 21.000
[product_id] => 1120280
)
[1] => stdClass Object
(
[gross_weight] => 41.000
[net_weight] => 21.000
[product_id] => 1120281
)
)
public function getGroupByData($data) {
$groups = array();
foreach ($data as $item) {
$key = $item['product_id'];
if (!array_key_exists($key, $groups)) {
$groups[$key] = array(
'id' => $item['product_id'],
'gross_weight' => $item['gross_weight'],
'net_weight' => $item['net_weight'],
);
} else {
$groups[$key]['gross_weight'] = $groups[$key]['gross_weight'] + $item['gross_weight'];
$groups[$key]['net_weight'] = $groups[$key]['net_weight'] + $item['net_weight'];
}
}
return $groups;
}
use php array as dictionary, and then just add the gross_weight and net_weight with += operator
$json = '
[
{
"gross_weight" : 20500,
"net_weight" : 10500,
"product_id" : 1120280
},
{
"gross_weight" : 20500,
"net_weight" : 10500,
"product_id" : 1120281
},
{
"gross_weight" : 20500,
"net_weight" : 10500,
"product_id" : 1120281
},
{
"gross_weight" : 20500,
"net_weight" : 10500,
"product_id" : 1120280
}
]
';
$x = json_decode($json);
var_dump($x);
$total = array();
foreach($x as $key => $val) {
if(empty($total[$val->product_id])) $total[$val->product_id] = array( "net_weight"=>0, "gross_weight"=>0, "product_id"=>$val->product_id );
$total[$val->product_id]["net_weight"] += $val->net_weight;
$total[$val->product_id]["gross_weight"] += $val->gross_weight;
}
$result = array_values($total);
var_dump($result);
result:
array(4) {
[0]=>
object(stdClass)#8 (3) {
["gross_weight"]=>
int(20500)
["net_weight"]=>
int(10500)
["product_id"]=>
int(1120280)
}
[1]=>
object(stdClass)#7 (3) {
["gross_weight"]=>
int(20500)
["net_weight"]=>
int(10500)
["product_id"]=>
int(1120281)
}
[2]=>
object(stdClass)#6 (3) {
["gross_weight"]=>
int(20500)
["net_weight"]=>
int(10500)
["product_id"]=>
int(1120281)
}
[3]=>
object(stdClass)#5 (3) {
["gross_weight"]=>
int(20500)
["net_weight"]=>
int(10500)
["product_id"]=>
int(1120280)
}
}
array(2) {
[0]=>
array(3) {
["net_weight"]=>
int(21000)
["gross_weight"]=>
int(41000)
["product_id"]=>
int(1120280)
}
[1]=>
array(3) {
["net_weight"]=>
int(21000)
["gross_weight"]=>
int(41000)
["product_id"]=>
int(1120281)
}
}
Related
My array data :
$opt_val =
Array
(
[0] => Array
(
[0] => Array
(
[0] => 0|0|0|P3D
[1] => 0|0|1|P4D
[2] => 0|0|2|P5D
)
[1] => Array
(
[0] => 0|1|0|P3D
[1] => 0|1|1|P4D
[2] => 0|1|2|P5D
)
)
[1] => Array
(
[0] => Array
(
[0] => 1|0|0|P3D
[1] => 1|0|1|P4D
[2] => 1|0|2|P5D
)
[1] => Array
(
[0] => 1|1|0|P3D
[1] => 1|1|1|P4D
[2] => 1|1|2|P5D
)
)
)
I want to join above array with result :
Array
(
[0] => Array
(
[0] => 0|0|0|P3D#0|1|0|P3D (from Array[0][0][0]#Array[0][1][0])
[1] => 0|0|1|P4D#0|1|1|P4D
[2] => 0|0|2|P5D#0|1|2|P5D
)
[1] => Array
(
[0] => 1|0|0|P3D#1|1|0|P3D (from Array[1][0][0]#Array[1][1][0])
[1] => 1|0|1|P4D#1|1|1|P4D
[2] => 1|0|2|P5D#1|1|2|P5D
)
)
My code
for ($ov = 0; $ov < count($opt_val); $ov++) {
for ($ovi = 0; $ovi < count($opt_val[$ov]); $ovi++) {
for ($iv = 0; $iv < count($opt_val[$ov][$iv]); $iv++) {
$im_opt_val[$iv] = implode("#", $opt_val[$ov][$ovi]);
}
$impl_opt_val[$ov] = $im_opt_val;
}
}
Thank you
The following code snippet should do the trick.
<?php
declare(strict_types=1);
$opt_val = [
[
[
'0|0|0|P3D',
'0|0|1|P4D',
'0|0|2|P5D',
],
[
'0|1|0|P3D',
'0|1|1|P4D',
'0|1|2|P5D',
],
],
[
[
'1|0|0|P3D',
'1|0|1|P4D',
'1|0|2|P5D',
],
[
'1|1|0|P3D',
'1|1|1|P4D',
'1|1|2|P5D',
],
],
];
$result = [];
foreach ($opt_val as $outerArrayKey => $outerArray) {
foreach ($outerArray as $innerArray) {
foreach ($innerArray as $innerArrayKey => $innerArrayElement) {
if (!isset($result[$outerArrayKey][$innerArrayKey])) {
$result[$outerArrayKey][$innerArrayKey] = $innerArrayElement;
} else {
$result[$outerArrayKey][$innerArrayKey] .= '#'.$innerArrayElement;
}
}
}
}
var_dump($result);
The output would be:
array(2) {
[0]=>
array(3) {
[0]=>
string(19) "0|0|0|P3D#0|1|0|P3D"
[1]=>
string(19) "0|0|1|P4D#0|1|1|P4D"
[2]=>
string(19) "0|0|2|P5D#0|1|2|P5D"
}
[1]=>
array(3) {
[0]=>
string(19) "1|0|0|P3D#1|1|0|P3D"
[1]=>
string(19) "1|0|1|P4D#1|1|1|P4D"
[2]=>
string(19) "1|0|2|P5D#1|1|2|P5D"
}
}
I hope this work for you:
$finalFinalArray = [];
foreach($outerArray as $key => $innerArray){
$finalArray = [];
$inQueueArray = [];
foreach ($innerArray as $inInnerArray) {
$inQueueArray = array_merge($inQueueArray, $inInnerArray);
}
// Now, inner array is merged
for ($i = 0; $i < count($inQueueArray); $i++){
$finalArray[] = $inQueueArray[$i] + "#" + $inQueueArray[$i+3];
}
$finalFinalArray[] = $finalArray;
}
var_dump($finalFinalArray);
Didn't test it!
This question already has answers here:
Implode two-dimensional array in PHP
(3 answers)
How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]
(23 answers)
Closed 4 years ago.
i just want to make two index array to be one array.
this is my code:
$intdate=array();
$arr=0;
foreach ($cek_cutay as $key => $value) {
$intdate[] =intervalDate($value->tgl_cuti_awal,$value->tgl_cuti_akhir);
$intdate[$arr++];
}
the result like :
array(2) {
[0]=> array(4) {
[0]=> string(10) "2018-11-12"
[1]=> string(10) "2018-11-13"
[2]=> string(10) "2018-11-14"
[3]=> string(10) "2018-11-15"
}
[1]=> array(2) {
[0]=> string(10) "2018-10-31"
[1]=> string(10) "2018-11-01"
}
}
i hope to be like :
array(5){
[0]=> string(10) "2018-11-12"
[1]=> string(10) "2018-11-13"
[2]=> string(10) "2018-11-14"
[3]=> string(10) "2018-11-15"
[4]=> string(10) "2018-10-31"
[5]=> string(10) "2018-11-01"
}
Thank you..!!
If the return from the intervalDate function is an array, you can do this
$intdate=array();
$arr=0;
foreach ($cek_cutay as $key => $value) {
foreach (intervalDate($value->tgl_cuti_awal,$value->tgl_cuti_akhir) as $date) {
$intdate[] = $date;
}
}
I think you expected to merge two array into a single array. If so then array_reduce might help you simply.
$arr = [
[
"2018-11-12",
"2018-11-13",
"2018-11-14",
"2018-11-15" ,
],
[
"2018-10-31",
"2018-11-01",
]
];
$intdate = array_reduce($arr, function($old, $new) {
return array_merge($old, $new);
}, []);
echo '<pre>', print_r($intdate), '</pre>';
You could use this function
function flatten_array( array $array, array $flattened = array() ) {
foreach ( $array as $item ) {
if ( is_array($item) ) {
$flattened = flatten_array( $item, $flattened );
continue;
}
$flattened[] = $item;
}
return $flattened;
}
$arr = array(
array(
"2018-11-12",
"2018-11-13",
"2018-11-14",
"2018-11-15" ,
),
array(
"2018-10-31",
"2018-11-01",
),
);
flatten_array($arr);
$arr1 = array(1,2,3,4,5,11);
$arr2 = array(6,7,8,9,10,11);
echo'<pre>';print_r(array_merge($arr1,$arr2));
echo'<pre>';print_r(array_unique(array_merge($arr1,$arr2)));die;
respective output :
array_merge :
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 11
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
)
array_unique + array_merge :
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 11
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
)
I'm trying to add each <outfit>Subnodes</outfit> subnodes to an array using php.
My actual code:
public static function get_outfits($username) {
$files = self::user_files($username);
$data = self::request($files['outfits']);
$data = #simplexml_load_string($data);
if ( $data && count(#$data->xpath('//outfits/outfit')) > 0 ) {
foreach(#$data->xpath('//outfits/outfit/*') as $items) {
$response['outfits']['items'][] = array(
"url" => (string)$items['url'],
"c" => (string)$items['c'],
"c2" => (string)$items['c2'],
"displayName" => (string)$items['displayName'],
"z" => (string)$items['z'],
"id" => (string)$items['id'],
"isUgc" => (string)$items['isUgc']
);
}
}
return (isset($response) ? $response : false);
}
The xml document looks like the following: http://outfits.zwinky.com/users/220/287/_perverted/outfits.xml
Sadly the code is saving every existing child into one array. But I'm trying to create an array index for each <outfit></outfit> node which should contain the child elements.
For example:
Array[0] = Everything between the first <outfit><outfit>
Array[1] = Everything between the second <outfit><outfit>
Does anyone have an idea, how to create this?
You need two loops, one for the outfit elements and one for the inner item elements. On the other side, you don't need the condition, because iterating an empty array/node list works fine.
$outfits = new SimpleXmlElement($xml);
$result = [];
foreach ($outfits->xpath('outfit') as $outfit) {
$items = [];
foreach ($outfit->xpath('*') as $item) {
$items[$item->getName()] = [
"url" => (string)$item['url'],
"c" => (string)$item['c'],
"c2" => (string)$item['c2'],
"displayName" => (string)$item['displayName'],
"z" => (string)$item['z'],
"id" => (string)$item['id'],
"isUgc" => (string)$item['isUgc']
];
}
$result[] = [
'name' => (string)$outfit['name'],
'items' => $items
];
}
var_dump($result);
Output:
array(14) {
[0]=>
array(2) {
["name"]=>
string(6) "babe13"
["items"]=>
array(14) {
["head"]=>
array(7) {
["url"]=>
string(51) "http://.../assets/babe/heads/01/head1"
["c"]=>
string(8) "0xF4C4A4"
["c2"]=>
string(8) "0xffffff"
["displayName"]=>
string(0) ""
["z"]=>
string(5) "33000"
["id"]=>
string(0) ""
["isUgc"]=>
string(0) ""
}
["face"]=>
array(7) {
["url"]=>
string(50) "http://.../assets/babe/faces/01/grl1"
["c"]=>
string(3) "0x0"
["c2"]=>
string(8) "0xFF0000"
["displayName"]=>
string(5) "girl1"
["z"]=>
string(5) "34000"
["id"]=>
string(8) "20014794"
["isUgc"]=>
string(0) ""
}
...
If this is the output you want :-
Array
(
[0] => Array
(
[url] => http://assets.zwinky.com/assets/babe/heads/01/head1
[c] => 0xF4C4A4
[c2] => 0xffffff
[displayName] =>
[z] => 33000
[id] =>
[isUgc] =>
)
[1] => Array
(
[url] => http://assets.zwinky.com/assets/babe/faces/01/grl1
[c] => 0x0
[c2] => 0xFF0000
[displayName] => girl1
[z] => 34000
[id] => 20014794
[isUgc] =>
)
[2] => Array
(
[url] => http://assets.zwinky.com/assets/babe/midsections/01/ms1
[c] => 0xBCE4FE
[c2] =>
[displayName] =>
[z] => 9000
[id] =>
[isUgc] =>
)
... etc etc
Then all you need to do is change the code to this
public static function get_outfits($username) {
$files = self::user_files($username);
$data = self::request($files['outfits']);
$data = #simplexml_load_string($data);
if ( $data && count(#$data->xpath('//outfits/outfit')) > 0 ) {
foreach(#$data->xpath('//outfits/outfit/*') as $items) {
// $response['outfits']['items'][] = array(
$response[] = array(
"url" => (string)$items['url'],
"c" => (string)$items['c'],
"c2" => (string)$items['c2'],
"displayName" => (string)$items['displayName'],
"z" => (string)$items['z'],
"id" => (string)$items['id'],
"isUgc" => (string)$items['isUgc']
);
}
}
return (isset($response) ? $response : false);
}
I want to apologize in advanced if this was already asked, I'm not exactly sure what this would be called.
I'm storing data from a form into a MongoDB database and I'd like to create defined key-value pairs to make sorting easier.
Using this code I am able to do this with a one-dimensional array, but it does not work with multidimensional arrays:
/* $array = The array */
$new_array = array();
foreach ($array as $key => $value) {
array_push($new_array, array(
'name' => $key,
'value' => $value
));
}
Example:
Input array:
Array
(
[email] => test#mail.com
[name] => John
[sports] => Array
(
[outdoor] => Array
(
[0] => Football
[1] => Baseball
)
[indoor] => Array
(
[0] => Basketball
[1] => Hockey
)
)
)
Output array:
Array
(
[0] => Array
(
[name] => email
[value] => test#mail.com
)
[1] => Array
(
[name] => name
[value] => John
)
[2] => Array
(
[name] => sports
[value] => Array
(
[outdoor] => Array
(
[0] => Football
[1] => Baseball
)
[indoor] => Array
(
[0] => Basketball
[1] => Hockey
)
)
)
)
Notice how it stops at the sports value array and does not change the array within it. How can I continue this pattern throughout all the arrays within it?
You can use recursion:
function keyValue($array){
$new_array = array();
foreach ($array as $key => $value) {
array_push($new_array, array(
'name' => $key,
'value' => is_array($value) ? keyValue($value) : $value
));
}
return $new_array;
}
Try this on for size:
$array = array(
'email' => 'test#email.com',
'name' => 'John',
'sport' => array('Soccor', 'Hockey')
);
$func = function($value, $key) {
$return = array();
$return['name'] = $key;
$return['value'] = $value;
return $return;
};
$parsed = array_map($func, $array, array_keys($array));
For me, this returned:
array(3) {
[0]=>
array(2) {
["name"]=>
string(5) "email"
["value"]=>
string(14) "test#email.com"
}
[1]=>
array(2) {
["name"]=>
string(4) "name"
["value"]=>
string(4) "John"
}
[2]=>
array(2) {
["name"]=>
string(5) "sport"
["value"]=>
array(2) {
["outdoor"]=>
array(2) {
[0]=>
string(8) "Football"
[1]=>
string(8) "Baseball"
}
["indoor"]=>
array(2) {
[0]=>
string(10) "Basketball"
[1]=>
string(6) "Hockey"
}
}
}
}
It is pretty simple to turn associative arrays to JSON objects (StdClass) and vice versa, preserving native data types (int, float, bool). Here's my attempt:
To Key-Value Array
function toKeyValue($values)
{
$result = [];
foreach ($values as $key => $value)
{
if (is_array($value)) {
$result[$key] = toKeyValue($value);
} elseif (is_object($value)) {
$result[$key] = toKeyValue((array) $value);
} else {
$result[$key] = $value;
}
}
return $result;
}
To JSON Object
function toJson($values)
{
return json_decode(json_encode($values));
}
$values should always be an array.
So I'm working on a website with Doctrine as ORM and I get the following array back as a result:
Array (
[0] => Array (
[c_cat_id] => 1
[c_title] => Programas e projetos
[p_menu] => PBA BR 163
[p_page_id] => 1
)
[1] => Array (
[c_cat_id] => 1
[c_title] => Programas e projetos
[p_menu] => Outros projetos
[p_page_id] => 3
)
)
Is it possible to transform this array (in PHP) to something like this:
Array (
[0] => Array (
[c_cat_id] => 1
[c_title] => Programas e projetos
[pages] => Array (
[0] => Array (
[p_page_id] => 1
[p_menu] => PBA BR 163
)
[1] => Array (
[p_page_id] => 3
[p_menu] => Outros projetos
)
)
)
)
Thanks for your help, always eager to learn new ways of doing things and that's why I love StackOverflow ;)
Tested and working:
Code:
$original = array(
array(
"c_cat_id" => "1",
"c_title" => "Programas e projetos",
"p_menu" => "PBA BR 163",
"p_page_id" => "1"),
array(
"c_cat_id" => "1",
"c_title" => "Programas e projetos",
"p_menu" => "Outros projetos",
"p_page_id" => "3"),
array(
"c_cat_id" => "2",
"c_title" => "Another Cat",
"p_menu" => "Outros projetos",
"p_page_id" => "4"),
);
$result = array();
foreach ($original as $row) {
$cat = $row['c_cat_id'];
if (!isset($result[$cat])) {
$result[$row['c_cat_id']] = array(
'c_cat_id'=>$row['c_cat_id'],
'c_title'=>$row['c_title'],
'pages'=>array(),
);
}
unset($row['c_cat_id'],$row['c_title']);
$result[$cat]['pages'][] = $row;
}
var_dump($result);
Result:
array(2) {
[1]=>
array(3) {
["c_cat_id"]=>
string(1) "1"
["c_title"]=>
string(20) "Programas e projetos"
["pages"]=>
array(2) {
[0]=>
array(2) {
["p_menu"]=>
string(10) "PBA BR 163"
["p_page_id"]=>
string(1) "1"
}
[1]=>
array(2) {
["p_menu"]=>
string(15) "Outros projetos"
["p_page_id"]=>
string(1) "3"
}
}
}
[2]=>
array(3) {
["c_cat_id"]=>
string(1) "2"
["c_title"]=>
string(11) "Another Cat"
["pages"]=>
array(1) {
[0]=>
array(2) {
["p_menu"]=>
string(15) "Outros projetos"
["p_page_id"]=>
string(1) "4"
}
}
}
}
It looks like you want to take an Array of pages and turn it into an array of categories with each containing an array of pages.
$inputArray = array(...); // whatever you have originally
$catArray = array();
foreach($inputArray as $page) {
addToCatArray($page);
}
function addToCatArray($page) {
$found = false;
foreach($catArray as $cat) {
if ($cat['c_cat_id'] == $page['c_cat_id'] {
$newPage = array('p_page_id' => $page['p_page_id'], 'p_menu' => $page['p_menu']);
$cat['pages'][] = $newPage;
$found = true;
break;
}
}
if (!$found) { // create a new category
$newCat = array('c_cat_id' => $page['c_cat_id'], 'c_title' => $page['c_title']);
$newPage = array('p_page_id' => $page['p_page_id'], 'p_menu' => $page['p_menu']);
$newCat['pages'] = array($newPage);
$catArray[] = $newCat;
}
}