I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);
Related
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));
Trying to add a bunch of array values together, keeping the ID value....
I thought I could use a basic foreach with a += operator, but it's not working out.
Here are my arrays:
Array(
[0] => Array(
[246] => Array(
[amount] => 2
)
)
)
Array(
[0] => Array(
[245] => Array(
[amount] => 1
)
)
)
Array(
[0] => Array(
[243] => Array(
[amount] => 2
)
)
)
Array(
[0] => Array(
[245] => Array(
[amount] => 1
)
)
)
Array(
[0] => Array(
[243] => Array(
[amount] => 2
)
)
)
What I'm trying to get is:
array(
'243' => '4',
'245' => '2',
'246' => '2',
);
And here's what I was attempting:
$sumArray = array();
foreach ($orgArray[0] as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$k]+=$value;
}
}
Here is what I'm getting:
Array
(
[243] => 2
)
You simply need to modify your foreach loops as you're trying to set $key which is the index of the arrays which for the example above would be 0,1,2,3...etc not 246,245,243...etc as you expect.
This is what you want.
$orgArray = [
[246 => ['amount' => 2]],
[245 => ['amount' => 1]],
[243 => ['amount' => 2]],
[245 => ['amount' => 1]],
[243 => ['amount' => 2]],
];
$sumArray = array();
foreach ($orgArray as $k => $subArray) {
foreach ($subArray as $id => $item) {
if (!isset($sumArray[$id])) {
$sumArray[$id] = 0;
}
$sumArray[$id] += $item['amount'];
}
}
Note: The above [] array identifier is assuming you're using the correct php version that allows it, otherwise you'd have to change them to array()
Which returns:
Array
(
[246] => 2
[245] => 2
[243] => 4
)
As expected.
EXAMPLE
I have this array:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 10
)
[2] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 18
)
)
How I can get another array:
- Grouping the TaxeName and the TaxeAmount and
- Making the sum of the amount Price ?
Like this:
Array (
[0] => Array (
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array (
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)
It can be done with a nested foreach:
$original = array(.......); // your current array
$newArr = array();
foreach($original as $origVal){
$exists = false;
foreach($newArr as $key => $newVal){
if($newVal['TaxeName'] == $origVal['TaxeName']){
$newArr[$key]['Price'] += $origVal['Price'];
$exists = true;
break;
}
}
if(!$exists){
$newArr[] = $origVal;
}
}
Outputs
Array
(
[0] => Array
(
[TaxeName] => TPS
[TaxeAmount] => 7
[Price] => 14
)
[1] => Array
(
[TaxeName] => TVQ
[TaxeAmount] => 9.975
[Price] => 28
)
)
Something like this maybe:
$final = array();
foreach ($arr as $subarr)
{
if (!isset($final[$subarr['TaxeName']]))
{
$final[$subarr['TaxeName']] = array('Price' => 0);
}
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeAmount'];
$final[$subarr['TaxeName']]['TaxeName'] = $subarr['TaxeName'];
$final[$subarr['TaxeName']]['Price'] = $final[$subarr['TaxeName']]['Price'] + $subarr['Price'];
}
The idea is to make a new array with the values that you need and initializing it with the price set to 0 so you can increment it in the foreach
You can do it like this also:
<?php
// Source
$myData = array(
array(
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 10,
),
array(
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 18,
)
);
// Helper Function
function parseData($data)
{
$parsedData = array();
if (is_array($data)) {
foreach ($data as $dataItem) {
if (!array_key_exists($dataItem['TaxeName'], $parsedData)) {
$parsedData[$dataItem['TaxeName']] = array(
'TaxeName' => $dataItem['TaxeName'],
'TaxeAmount' => $dataItem['TaxeAmount'],
'Price' => floatval($dataItem['Price'])
);
} else {
$parsedData[$dataItem['TaxeName']]['Price'] += floatval($dataItem['Price']);
}
}
}
return array_values($parsedData);
}
// Test
$parsed_data = parseData($myData);
var_dump($parsed_data);
?>
Outputs:
Just use this function, input is your array, output is the array you required:
function calculate(array $input){
$output = [];
foreach ($input as $v){
if (array_key_exists($v['TaxeName'], $output)){
$output[$v['TaxeName']]['Price'] += $v['Price'];
} else {
$output[$v['TaxeName']] = $v;
}
}
return array_values($output);
}
I know that solutions with external classes are not welcome here on SO. I'm showing this just to illustrate the "Grouping the TaxeName and the TaxeAmount" task.
//use class tablearray from https://github.com/jspit-de/tableArray
$data = [
['TaxeName' => 'TPS', 'TaxeAmount' => 7, 'Price' => 14],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 10],
['TaxeName' => 'TVQ', 'TaxeAmount' => 9.975, 'Price' => 18],
['TaxeName' => 'TVQ', 'TaxeAmount' => 19.975, 'Price' => 23]
];
$newData = tableArray::create($data)
->filterGroupSum('Price',['TaxeName','TaxeAmount'])
->fetchAll()
;
echo '<pre>';
var_export($newData);
Output:
array (
0 =>
array (
'TaxeName' => 'TPS',
'TaxeAmount' => 7,
'Price' => 14,
),
1 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 9.975,
'Price' => 28,
),
2 =>
array (
'TaxeName' => 'TVQ',
'TaxeAmount' => 19.975,
'Price' => 23,
),
)
I have this PHP array:
Array(
[0] => Array(
["Import"]=> Array
(
[0] => 1.00
[1] => 2.00
[2] => 1.00
[3] => 9.00
)
["Page"] => Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 6
)
["Key"] => Array
(
[0] => 1
[1] => 22
[2] => 88
[3] => 3
)
)
)
I need to get:
Array(
[0] => Array(
[0] => Array(
["Import"] => 1.00
["Page"] => 1
["Key"] => 1
)
[1] => Array(
["Import"] => 2.00
["Page"] => 4
["Key"] => 22
)
[2] => Array(
["Import"] => 1.00
["Page"] => 5
["Key"] => 88
)
[3] => Array(
["Import"] => 9.00
["Page"] => 6
["Key"] => 3
)
)
)
I've checked array_merge and array_combine but I can't find a way to use them in this case.
How can I do?
Try this. Seems to work as you expect.
<?php
$source = array(
array(
'Imports' => array(
1.00,2.00,1.00, 9.00),
'Page' => array(
1,4,5,6),
'Key' => array(
1,22,88,3)
)
);
print_r($source);
$dest = array();
foreach($source as $key => $src) {
foreach($src as $typeKey => $typeArr) {
foreach($typeArr as $index => $val){
$dest[$key][$index][$typeKey] = $val;
}
}
}
print_r($dest);
?>
Here is a demo: http://codepad.org/bht4ne7K
In PHP 5.5 you can easily achieve that with array_column() function:
$array = [
'Imports' => ['i0', 'i1'],
'Page' => ['p0', 'p1'],
'Key' => ['k0', 'k1']
];
$i = 0;
$result = array_map(function($x) use ($array, &$i)
{
return array_combine(array_keys($array), array_column($array, $i++));
}, current($array));
//var_dump($result);
-but for earlier versions you'll need to gather your array with foreach like:
$result = [];
foreach($array as $key=>$item)
{
foreach($item as $i=>$value)
{
$result[$i][$key] = $value;
}
}
//var_dump($result);
-you'll need, of course, do that with each element of your parent array (code above is a sample of how to rearrange 2-level array). That, again, can be easily done with array_map()
Something like this:
function switchKeys(Array $input) {
$result = array();
foreach ($input as $field => $data) {
if (is_array($data)) {
foreach ($data as $index => $value) {
$result[$index][$field] = $value;
}
}
}
return $result;
}
$input = array(
"imports" => array(1.00, 2.00, 1.00, 9.00,),
"page" => array(1, 4, 5, 6,),
"key" => array(1, 22, 88, 3,),
);
$output = switchKeys($input);
var_export($input);
var_export($output);
Note that your input array has one more level, so you should call the function for each sub array
I have the following array which I would like to edit:
Array
(
[qty_black_34] =>
[qty_black_36] => 2
[qty_black_38] =>
[qty_black_40] =>
[qty_black_42] =>
[qty_black_44] =>
[qty_black_48] =>
[qty_powder_34] =>
[qty_powder_36] =>
[qty_powder_38] =>
[qty_powder_40] =>
[qty_powder_42] => 1
[qty_powder_44] =>
[qty_powder_48] =>
[qty_red_34] =>
[qty_red_36] =>
[qty_red_38] => 2
[qty_red_40] =>
[qty_red_42] =>
[qty_red_44] =>
[qty_red_48] => )
What I want to do is to build another array to hold only the elements with a value.
The new array must look like this"
Array
(
[0] => Array
(
[color] => black
[size] => 36
[quantity] => 2
)
[1] => Array
(
[color] => powder
[size] => 42
[quantity] => 1
)
[2] => Array
(
[color] => red
[size] => 38
[quantity] => 2
)
)
PHP is the language I'm using.
loop through array and take elements, which have set a value. for the additional key/values in your final array split the string used as key in original array
$new_array = array();
foreach ($old_array as $key => value) {
if ($value) {
$key_split = explode('_', $key);
$new_array[] = array('color' => $key_split[1], 'size' => $key_split[2], 'quantity' => $value);
}
}
$products = array();
foreach($quantities as $key => $quantity){
if($quantity != '') {
list($q, $color, $size) = explode('_', $key);
$products[] = array(
'color' => $color,
'size' => $size,
'quantity' => $quantity
);
}
}
Demo