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
Related
i have data array, and this my array
Array
(
[0] => Array
(
[id] => 9,5
[item] => Item A, Item B
)
[1] => Array
(
[id] => 3
[item] => Item C
)
)
in array 0 there are two ID which I separated using a comma, I want to extract the data into a new array, how to solve this?
so the output is like this
Array
(
[0] => Array
(
[id] => 9
[item] => Item A
)
[1] => Array
(
[id] => 3
[item] => Item C
)
[2] => Array //new array
(
[id] => 5
[item] => Item B
)
)
this my code
$arr=array();
foreach($myarray as $val){
$arr[] = array(
'id' => $val['id'],
'item' => $val['item'],
);
}
echo '<pre>', print_r($arr);
$arr = [
array(
'id' => '9,5',
'item' => 'Item A, Item B'
),
array(
'id' => 3,
'item' => 'Item C'
)
];
$newArr = array_reduce($arr, function($tmp, $ele){
$arrIds = explode(',', $ele['id']);
$arrItems = explode(',', $ele['item']);
forEach($arrIds as $key => $arrId) {
$tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
}
return $tmp;
});
The code down below should do the job. But I didn't understand why you didn't create those items seperately in the first place.
foreach ($arr as $i => $data) {
if (!str_contains($data['id'], ',')) continue;
$items = explode(',', $data['item']);
foreach(explode(',', $data['id']) as $i => $id) {
$new = ['id' => $ids[$i], 'item' => $items[$i]];
if ($i) $arr[] = $new;
else $arr[$i] = $new;
}
}
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));
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 the next array:
Array
(
[1000] => Array
(
[pv] => 81
)
[1101] => Array
(
[1102] => Array
(
[pv] => 33
)
[1103] => Array
(
[pv] => 15
)
[pv] => 72
)
)
I want to make new array from this like this:
Array(
[1000] => Array(['generation'] => 1, ['pv'] => 81)
[1101] => Array(['generation'] => 1, ['pv'] => 72)
[1102] => Array(['generation'] => 2, ['pv'] => 33)
[1103] => Array(['generation'] => 2, ['pv'] => 15)
)
Generation is a level of array's deep. There are a lot of levels.
Thanks.
Be creative...
function coffee($elm, $cur_key=NULL, $level=0, &$push_arr=NULL){
if(!is_array($push_arr)) $pusH_arr = array();
$level++;
foreach($elm as $key=>$val){
if($key == 'pv'){
$push_arr[$cur_key] = array(
'generation' => $level,
'pv' => $val
);
}
else if(is_array($val)){
coffee($val, $key, $level, $push_arr);
}
else{
// unexpected value
}
}
return $push_arr;
}
// Usage:
$normalised_array = coffee($array_from_your_question);