convert flat array into multidimensional array in php - php

I am trying to convert a flat array into multidimensional array based on 'parent' and look a lot of examples and get good results but have 1 issue. I am missing last time of the array.
first i created an flat array
$service_arr = array();
foreach( $order_info[0]['service'] as $ordered_service ) {
$s_id = $ordered_service['id'];
$s_name = $ordered_service['name'];
$s_qty = $ordered_service['qty'];
$s_price = $ordered_service['price'];
$s_parent = gp_get_item_parent( $s_id ); // return parent_id of the element.
$service_arr[] = array(
'id' => $s_id,
'name' => $s_name,
'qty' => $s_qty,
'price' => $s_price,
'parent' => $s_parent
);
}
and this return's a flat array
Result:
Array
(
[0] => Array
(
[id] => 29
[name] => Another Facial
[qty] => 1
[price] => 1800
[parent] => 16
)
[1] => Array
(
[id] => 17
[name] => Facial 1
[qty] => 1
[price] => 2000
[parent] => 16
)
[2] => Array
(
[id] => 26
[name] => Addon
[qty] => 1
[price] => 500
[parent] => 17
)
[3] => Array
(
[id] => 39
[name] => Another Addon
[qty] => 1
[price] => 150
[parent] => 17
)
[4] => Array
(
[id] => 18
[name] => Facial 2
[qty] => 1
[price] => 2000
[parent] => 16
)
[5] => Array
(
[id] => 38
[name] => Nice Facial
[qty] => 1
[price] => 3000
[parent] => 16
)
[6] => Array
(
[id] => 21
[name] => Massage 2
[qty] => 1
[price] => 6000
[parent] => 14
)
)
Converting flat into multidimension array:
function create_tree_array( &$list, &$output, $parent_id ) {
if ( ! is_array( $list ) ) {
return;
}
if ( ! is_array( $output ) ) {
return;
}
foreach( $list as $i => $item ) {
if ( $item['parent'] == $parent_id ) {
$item['addon'] = array();
create_tree_array( $list, $item['addon'], $item['id'] );
$output[] = $item;
}
}
}
And using this function like
$services_tree = array();
create_tree_array( $service_arr, $services_tree, $service_arr[0]['parent'] );
Its working but the issue is that its missing last item of array:
[6] => Array (
[id] => 21
[name] => Massage 2
[qty] => 1
[price] => 6000
[parent] => 14
)

Related

Move a child array to parent array and change parent/child name

I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.
ok I have this array
Array
(
[0] => Array
(
[Data3] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[Data3] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
)
[ammount] => 2
[Data_id] => 3
)
[2] => Array
(
[Data4] => Array
(
[id] => 3
[category] => Whiskey
[name] => Some name Gold
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 4
)
[3] => Array
(
[Data4] => Array
(
[id] => 5
[category] => Vodka
[name] => Something Blue 100 cl
[description] => description
[image] => Something.jpg
[price] => 32.44
)
[ammount] => 1
[Data_id] => 4
)
)
What I would like to be the result is something like this:
Array
(
[0] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
[ammount] => 2
[Data_id] => 3
)
[2] => Array
(
[id] => 3
[category] => Whiskey
[name] => Some name Gold
[description] => description
[image] => asdf.jpg
[price] => 83.99
[ammount] => 1
[Data_id] => 4
)
[3] => Array
(
[id] => 5
[category] => Vodka
[name] => Something Blue 100 cl
[description] => description
[image] => Something.jpg
[price] => 32.44
[ammount] => 1
[Data_id] => 4
)
)
or another way I could work with is if I can change Data1, Data2, Data3 and so on ..
can be n Data depends how many producs a user select
into a same name ex simple Data or Info.
ex:
Array
(
[0] => Array
(
[Info] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[Info] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
)
[ammount] => 2
[Data_id] => 3
)
Any solution will be fine for me.
Thanks and regards
Use this code for your result:
$final_array = array();
foreach($array1 as $offset1 => $array2) {
$tmp_array = array();
foreach($array2 as $offset2 => $array3) {
if(is_array($array3)) {
$tmp_array = $array3;
} else {
$tmp_array[$offset2] = $array3
}
}
$final_array = array_merge($final_array, $tmp_array;);
//or
$final_array[] = $tmp_array;
}
I would do this this way. However I would look to fix why the data is in that structure to begin with.
$aStartArray = array(array('Data3'=>array('id'=>1, 'cat'=>2), 'amount' => 1, 'Data_id'=>3));
foreach ($aStartArray as $iPos => $aArray) {
$aKeys = array_keys($aArray); // fetches all the keys
$aFirstElement = $aArray[$aKeys[0]]; // Get the first element using first key
// assign/ overwrite data at the same position
$aStartArray[$iPos] = array($aFirstElement, 'amount' => $aArray['amount'], 'Data_id' => $aArray['Data_id']);
}
echo "<pre>";
var_dump($aStartArray);
your first option:
foreach($arr as $key => $value){
foreach($value as $k => $val){
if(is_array($val)){
$arr[$key] = $val;
unset($arr[$key][$k]);
}
}
}
echo "<pre>"; print_r($arr);
Check output here
This is the best algorithm
const moveArrayToParentArray = (input) => {
let finalOutput = []
input.forEach((e) => {
if (Array.isArray(e)) {
finalOutput = [...finalOutput, ...e];
} else {
finalOutput = [...finalOutput, e];
}
})
return finalOutput
}
const array = ['a', 'b']
const array2 = [array]
const array3 = [array, "c"]
console.log(moveArrayToParentArray(array))
console.log("----------------------------")
console.log(moveArrayToParentArray(array2))
console.log("----------------------------")
console.log(moveArrayToParentArray(array3))
console.log("----------------------------")

How to reformat an array using php?

I have the following array:
Array
(
[0] => Array
(
[Import] => Array
(
[id] => 1
[category_id] => 2
[product_id] => 2
[amount] => 50
[cost] => 8320
[comment] => transportation and others cost: 100
[created] => 2015-06-23 19:21:10
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[1] => Array
(
[Import] => Array
(
[id] => 2
[category_id] => 2
[product_id] => 2
[amount] => 15
[cost] => 3000
[comment] =>
[created] => 2015-06-22 18:10:36
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[2] => Array
(
[Import] => Array
(
[id] => 3
[category_id] => 2
[product_id] => 1
[amount] => 15
[cost] => 2000
[comment] =>
[created] => 2015-06-23 19:20:15
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 0
[confirmed] => 0
[canceled] => 0
)
)
)
I want to remove duplicate value of same product_id inside [Import][product_id] but want sum [Import][amount]. My expected array is:
Array
(
[0] => Array
(
[Import] => Array
(
[id] => 1
[category_id] => 2
[product_id] => 2
[amount] => 65
[cost] => 8320
[comment] => transportation and others cost: 100
[created] => 2015-06-23 19:21:10
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 1
[confirmed] => 2
[canceled] => 0
)
)
[1] => Array
(
[Import] => Array
(
[id] => 3
[category_id] => 2
[product_id] => 1
[amount] => 15
[cost] => 2000
[comment] =>
[created] => 2015-06-23 19:20:15
)
[0] => Array
(
[total_sell] => 10
[no_contact] => 0
[confirmed] => 0
[canceled] => 0
)
)
)
It will be really a gift if anyone give a function to solve this issue.
$filteredArray = [];
foreach ($array as $productData) {
if (isset($filteredArray[$productData['Import']['product_id']])) {
$filteredArray[$productData['Import']['product_id']]['Import']['amount'] += $productData['Import']['amount'];
}
else {
$filteredArray[$productData['Import']['product_id']] = $productData;
}
}
print_r($filteredArray);
Ah.. forgot to mention - $array is Your base array.
/**
* Removes duplicate summing amount from products array
*
* #param array $array
* #return array
*/
function removeDuplicates($array)
{
$idsCount = array();
foreach ($array as $key => $value) {
$idsCount[$value['Import']['product_id']]['count'] += 1;
$idsCount[$value['Import']['product_id']]['sum'] += $value['Import']['amount'];
if ($idsCount[$value['Import']['product_id']]['count'] > 1) {
unset($array[$key]);
$array[$idsCount[$value['Import']['product_id']]['key']]['Import']['amount'] = $idsCount[$value['Import']['product_id']]['sum'];
} else {
$idsCount[$value['Import']['product_id']]['key'] = $key;
}
}
return $array;
}
i know it looks crazy but is formatted on your specific array.

How to remove duplicate data in an array?

I have the following array:
Array
(
[0] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 1
[category_id] => 1
[amount] => 50
[cost] => 8320
[paid] => 0
[comment] => transportation and others cost: 100
[created] => 2015-06-22 12:09:20
)
[0] => Array
(
[total_sell] => 6
)
)
[1] => Array
(
[Import] => Array
(
[product_id] => 2
[id] => 2
[category_id] => 2
[amount] => 15
[cost] => 3000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:36
)
[0] => Array
(
[total_sell] => 1
)
)
[2] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 3
[category_id] => 1
[amount] => 15
[cost] => 2000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:58
)
[0] => Array
(
[total_sell] => 6
)
)
[3] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 4
[category_id] => 1
[amount] => 50
[cost] => 8000
[paid] => 0
[comment] =>
[created] => 2015-06-23 01:10:10
)
[0] => Array
(
[total_sell] => 6
)
)
)
I want to remove duplicate entry of [Import][product_id]. So my expected result is :
Array
(
[0] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 1
[category_id] => 1
[amount] => 50
[cost] => 8320
[paid] => 0
[comment] => transportation and others cost: 100
[created] => 2015-06-22 12:09:20
)
[0] => Array
(
[total_sell] => 6
)
)
[1] => Array
(
[Import] => Array
(
[product_id] => 2
[id] => 2
[category_id] => 2
[amount] => 15
[cost] => 3000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:36
)
[0] => Array
(
[total_sell] => 1
)
)
)
Would you write a function to filter this type of array and produce expected result. I have been googling for 2 days but no luck.
This is a handy one liner that should do the trick:
$unique= array_map("unserialize", array_unique(array_map("serialize", $original)));
If the underlying arrays are not identical, that won't work, in which case I think you could do:
$unique = array_intersect_key($original ,
array_unique(
array_map(function($item) {
return $item['Import']['product_id'];
}, $original)
)
);
Tested: http://sandbox.onlinephpfunctions.com/code/8aee5cbd614e0ddd1a03dfaa7e98c72fbbe7d68d
Here is a quick stable sort and reduce which runs in linearithmic time. First-encountered product Id's are kept, and entries with duplicate product Id's are ignored.
// Stable sort
sort($in);
// Reduce
$out = array_reduce($in, function(&$acc, &$item){
if($item['Import']['product_id'] !== #$acc[sizeof($acc)-1]['Import']['product_id']) {
$acc[] = $item;
}
return $acc;
}, []);
Demo: http://ideone.com/BP0eUJ
Update: Here is an even better linear-time algorithm that does the same as above using a fast "hash table" lookup. Again, the first-encountered product Id is kept and subsequent ones of the same Id are ignored.
$out = [];
$hashTable = [];
foreach($in as $item) {
$pid = $item['Import']['product_id'];
if(!isset($hashTable[$pid])) {
$out[] = $item;
$hashTable[$pid] = true;
}
}
Demo: http://ideone.com/5RF0og

how to get array like this?

I have one array in php like this :
Array
(
[0] => Array
(
[name] => abc
[id] => 107
[CycleNumber] => 1
[Type] => People
)
[1] => Array
(
[name] => john
[id] => 312
[CycleNumber] => 5
[Type] => People
)
[2] => Array
(
[name] => jenny
[id] => 110
[CycleNumber] => 3
[Type] => People
)
[3] => Array
(
[name] => metting room
[id] => 590
[CycleNumber] => 4
[Type] => Facility
)
[4] => Array
(
[name] => projector
[id] => 470
[CycleNumber] => 4
[Type] => Facility
)
)
I want to replace the duplicate type with blank. but the first one should have that type name and others should have blank. so the result array should be like this :
Array
(
[0] => Array
(
[name] => abc
[id] => 107
[CycleNumber] => 1
[Type] => People
)
[1] => Array
(
[name] => john
[id] => 312
[CycleNumber] => 5
[Type] =>
)
[2] => Array
(
[name] => jenny
[id] => 110
[CycleNumber] => 3
[Type] =>
)
[3] => Array
(
[name] => metting room
[id] => 590
[CycleNumber] => 4
[Type] => Facility
)
[4] => Array
(
[name] => projector
[id] => 470
[CycleNumber] => 4
[Type] =>
)
)
I want array in this format only. and i am using PHP zend.
I search for this but most of them showing to remove that element from array. but i don't want to remove it. i want to replace it with blank but want to show the first one.
Tried Code
$result = array();
$result1 = array();
$result2 = array();
$y = array();
$y1 = array();
foreach ($data as $entry) {
$type= $entry["type"];
if (!isset($y[$type])) {
$y[$type] = array();
unset($entry["type"]);
$result[$type][] = $entry;
}
}
can anyone tell me how to do that ?
Code
$i = 0;
$found = 0;
foreach($data as $key=>&$val) {
if($i != 0) {
if($data[$i]['Type'] == $data[$found]['Type']) {
$data[$i]['Type'] = "";
}
else {
$found = $i;
}
}
$i++;
}
echo "<pre>";
print_r($data);
Output
Array
(
[0] => Array
(
[name] => abc
[id] => 107
[CycleNumber] => 1
[Type] => People
)
[1] => Array
(
[name] => john
[id] => 312
[CycleNumber] => 5
[Type] =>
)
[2] => Array
(
[name] => jenny
[id] => 110
[CycleNumber] => 3
[Type] =>
)
[3] => Array
(
[name] => metting room
[id] => 590
[CycleNumber] => 4
[Type] => Facility
)
[4] => Array
(
[name] => projector
[id] => 470
[CycleNumber] => 4
[Type] =>
)
)
Example

How do I access data within this multidimensional array?

I have this array:
$items_pool = Array (
[0] => Array ( [id] => 1 [quantity] => 1 )
[1] => Array ( [id] => 2 [quantity] => 1 )
[2] => Array ( [id] => 72 [quantity] => 6 )
[3] => Array ( [id] => 4 [quantity] => 1 )
[4] => Array ( [id] => 5 [quantity] => 1 )
[5] => Array ( [id] => 7 [quantity] => 1 )
[6] => Array ( [id] => 8 [quantity] => 1 )
[7] => Array ( [id] => 9 [quantity] => 1 )
[8] => Array ( [id] => 19 [quantity] => 1 )
[9] => Array ( [id] => 20 [quantity] => 1 )
[10] => Array ( [id] => 22 [quantity] => 1 )
[11] => Array ( [id] => 29 [quantity] => 0 )
)
I'm trying to loop through this array and perform a conditional based on $items_pool[][id]'s value. I want to then report back TRUE or NULL/FALSE, so I'm just testing the presence of to be specific.
Something like this:
$items_pool = array(...);
$result = false;
foreach ($items_pool as $item) {
if ('something' == $item['id']) {
$result = true;
break;
}
}
Loop through an check if anything is empty..
foreach($items_pool as $arr){
echo $arr['id'].'==>'.$arr['quantity'];
if($arr['quantity'] == 0){
echo 'id:'.$arr['id'].' is empty!';
return false;
}
}

Categories