I'm fairly new with PHP and I need help with adding certain row from JSON file.
For instance i have
Array
(
[0] => Array
(
[id] => 1
[name] => "Computer"
[price] => 1000
)
[1] => Array
(
[id] => 1
[name] => "Mouse"
[price] => 14
)
[2] => Array
(
[id] => 1
[name] => "Computer"
[price] => 1500
)
[3] => Array
(
[id] => 1
[name] => "Mouse"
[price] => 16
)
)
the output should be
Array(
[name] => "Computer"
[sum] => 2500
)
Array(
[name] => "Mouse"
[sum] => 30
)
I tried using this
$i = 0;
foreach ($array as $rows){
$i += $rows['price'];
}
but this one basically adds them all.
I appreciate the help!
Code
<?php
// make origin
$array_origin = array(
array('id' => 1,'name' => 'Computer','price' => 1000),
array('id' => 1,'name' => 'Mouse','price' => 14),
array('id' => 1,'name' => 'Computer','price' => 1500),
array('id' => 1,'name' => 'Mouse','price' => 16),
);
echo '<pre>' . var_export($array_origin, true) . '</pre><hr>';
// store name-price pair
$stack=array();
foreach ($array_origin as $index => $array_part) {
$stack[$array_part['name']]=array_key_exists($array_part['name'],$stack)?$stack[$array_part['name']]+$array_part['price']:$array_part['price'];
}
// make output
$j=0;
$output=array();
foreach ($stack as $name => $sum) {
$output[]=array(
'name' => $name,
'sum' => $sum
);
echo '<pre>' . var_export($output[$j], true) . '</pre>';
$j++;
}
Output
Or use json to make origin array
$json_str='[
{
"id":1,
"name":"Computer",
"price":"1000"
},
{
"id":1,
"name":"Mouse",
"price":14
},
{
"id":1,
"name":"Computer",
"price":1500
},
{
"id":1,
"name":"Mouse",
"price":16
}
]';
$array_origin=json_decode($json_str, true);
Hope it can help you ~
since you wrote all that out, I guess I can write you a quick loop.
$answer = array();
foreach($oldarray as $val)
{
#$answer[$val['name']] += $val['sum'];
}
print_r($answer);
It's not the exact answer, but it will get you there.
Try this code:
$result = [];
foreach ($array as $row) {
if (array_key_exists($row['name'], $result)) {
$result[$row['name']]['sum'] += $row['price'];
} else {
$result[$row['name']] = [
'name' => $row['name'],
'sum' => $row['price'],
];
}
}
print_r($result);
Related
i want to combine the values of array having same index name in foreach loop..
i tried array_combine but it returns the single array.
$data = $_POST['variable']; //it contain the values in an array
$result=array();
foreach ($data as $mycat){
$result = array_merge($result, $mycat);
}
echo "<pre>";print_r($result);echo "</pre>";
it returns only data in single array
Array
(
[vendor] => 1-Open Market
[priority] => 2
[demand_for_id] => 9
[ims_allocation_details_id] => 148
[temp_demand_id] => 1
)
as shown in attached picture item names are same, so when item names are same i want to combine the total values in foreach and insert only one record into database instead to two
enter image description here
the contents of $_POST['variable']; are
Array
(
[2] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 6
[priority] => 1
[item_name] => BAJRA MOTI
[amount] => 1000
[demand_for_id] => 9
[ims_allocation_details_id] => 153
)
[1] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 1
[priority] => 2
[item_name] => BAJRA MOTI
[amount] => 2500
[demand_for_id] => 9
[ims_allocation_details_id] => 148
)
)
You should replace
$result = array_merge($result, $mycat);
with
$result[] = array_merge($result, $mycat);
and it will not be single
UPDATE
$result = array();
foreach ($data as $mycat) {
if(!isset($result[$mycat['item_name']])) {
$result[$mycat['item_name']] = $mycat;
} else {
//do if needed
}
}
echo "<pre>";print_r($result);echo "</pre>";
You can create a custom function to solve your problem.
Example:
<?php
$array = [
[
'vendor' => '1-Open Market',
'temp_demand_id' => 6,
'priority' => 1,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 9,
'ims_allocation_details_id' => 153,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 1,
'priority' => 2,
'item_name' => 'BAJRA MOTI',
'amount' => 2500,
'demand_for_id' => 9,
'ims_allocation_details_id' => 148,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 5,
'priority' => 3,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 11,
'ims_allocation_details_id' => 200,
],
];
function array_merge_recursive_custom($array) {
$processed = null;
foreach ($array as &$subArray) {
if (empty($processed)) {
$processed = $subArray;
continue;
}
foreach ($subArray as $key => $value) {
if (is_numeric($value)) {
$subArray[$key] += $processed[$key];
}
}
$processed = $subArray;
}
return end($array);
}
var_dump(array_merge_recursive_custom($array));
Here is my collected array.
$raw_ar = Array (
0 => Array ( 'ID' => 6, 'pageTitle' => 'First', 'pageContent' => 'http://localhost/cms/1', 'parentID' => 0 ),
1 => Array ( 'ID' => 7, 'pageTitle' => 'Second', 'pageContent' => 'http://localhost/cms/2', 'parentID' => 6 ),
2 => Array ( 'ID' => 8, 'pageTitle' => 'Third', 'pageContent' => 'http://localhost/cms/3', 'parentID' => 6 ) ,
3 => Array ( 'ID' => 9, 'pageTitle' => 'Four', 'pageContent' => 'http://localhost/cms/4', 'parentID' => 0 )
) ;
And my result should be like this
$final_ar = array(
0 => array ( 'ID' => 6, 'pageTitle' => 'First', 'pageContent' => 'http://localhost/cms/1', 'parentID' => 0 ,
'sub_items' => array(
0 => array('ID' => 7, 'pageTitle' =>'second', 'pageContent' => 'http://localhost/cms/2', 'parentID' => 6),
1 => array('ID' => 8, 'pageTitle' => 'Third', 'pageContent' => 'http://localhost/cms/3', 'parentID' => 6),
)
),
1 => array('ID' => 9, 'pageTitle' => 'Four', 'pageContent' => 'http://localhost/cms/4', 'parentID' => 0)
);
And here is my code
$final_ar = array();
foreach ($raw_ar as $value) {
if($value['parentID'] ==0){
$final_ar[] = $value;
}
else{
$pID = $value['parentID'];
foreach ($final_ar as $value1) {
//echo $value1['ID'].'-'.$pID;
if($value1['ID'] == $pID){
//if(isset($value1['sub_items'])){
$value1['sub_items'][] = $value;
//}else
//$value1['sub_items'] = $value;
}
$temp_ar[] = $value1;
}
$exist = 0;
foreach ($final_ar as $key => $val) {
# code...
if($val['ID'] == $temp_ar['ID']){
unset($final_ar[$key]);
$final_ar[$key] = $temp_ar;
$exist =1;
break;
}
}
if($exist == 0)
$final_arr[] = $temp_ar;
//$parent_key = array_column($raw_ar,'ID', 'parentID');
}
}
print_r($final_arr);
And I tried to code it with sub_items . But it helps to create array. But I don't know how to remove existing array once it modifies. It gives the result like this.
Array ( [0] => Array ( [0] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 7 [pageTitle] => Second [pageContent] => http://localhost/cms/2 [parentID] => 6 ) ) ) ) [1] => Array ( [0] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 7 [pageTitle] => Second [pageContent] => http://localhost/cms/2 [parentID] => 6 ) ) ) [1] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 8 [pageTitle] => Third [pageContent] => http://localhost/cms/3 [parentID] => 6 ) ) ) ) )
Try this:
function formatArray($nonFormattedArray) {
$formattedArray = [];
$subItems = [];
foreach ($nonFormattedArray as $item) {
$pid = $item['parentID'];
if ($pid != 0) {
if (isset($subItems[$pid]))
$subItems[$pid][] = $item;
else
$subItems[$pid] = [$item];
} else
$formattedArray[] = $item;
}
foreach ($formattedArray as $key => $parent) {
resolveChild($formattedArray[$key], $subItems);
}
return $formattedArray;
}
function resolveChild(&$parent, &$subItems) {
//return if no child
if (!isset($subItems[$parent['ID']]))
return $parent;
foreach ($subItems[$parent['ID']] as $key => $child) {
if (isset($parent['sub_items']))
$parent['sub_items'][] = resolveChild($subItems[$parent['ID']][$key], $subItems);
else
$parent['sub_items'] = [resolveChild($subItems[$parent['ID']][$key], $subItems)];
}
return $parent;
}
Now, formatArray($nonFormattedArray) should return your desired answer.
This will be independent of the order of your parent and child items and will reduce the total iteration count and execution time.
This will produce an Array as deep as the inheritance in the data.
Note that execution time will increase with the increment in inheritance level.
So many code you have here.
Here's my version:
foreach ($raw_ar as $value) {
if ($value['parentID'] == 0) {
$final_ar[$value['ID']] = $value;
}
}
foreach ($raw_ar as $value) {
$parent_id = $value['parentID'];
if (0 < $parent_id) {
if (!isset($final_ar[$parent_id]['sub_items'])) {
$final_ar[$parent_id]['sub_items'] = [];
}
$final_ar[$parent_id]['sub_items'][] = $value;
}
}
$final_ar = array_values($final_ar); // if you need 0-indexed array
If you're 100% sure that parent items in your array come before child ones - you can join both foreaches into one:
foreach ($raw_ar as $value) {
$parent_id = $value['parentID'];
if ($parent_id == 0) {
$final_ar[$value['ID']] = $value;
} else {
if (!isset($final_ar[$parent_id]['sub_items'])) {
$final_ar[$parent_id]['sub_items'] = [];
}
$final_ar[$parent_id]['sub_items'][] = $value;
}
}
$final_ar = array_values($final_ar); // if you need 0-indexed array
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);
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