Convert PHP "grouped" array to "segmented" array - php

Trying to convert a "grouped" multidimensional array to a "segmented" multidimensional array. Not sure how to explain it exactly so hopefully these print_r results explain it better.
Current Array
Array
(
[qty] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[item_id] => Array
(
[0] => RR332
[1] => FF586
[2] => QW865
)
[item_name] => Array
(
[0] => Widget 1
[1] => Widget 2
[2] => Widget 3
)
[price] => Array
(
[0] => 1.00
[1] => 1.50
[2] => 1.50
)
)
Wanted Array
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
This seems like it should be a simple task but I haven't been able to crack it yet.
I would preferably like to loop through the Current Array to create the Wanted Array if possible.
Any help is greatly appreciated!
Thanks.

You mean this?:
$data = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1,
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865',
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3',
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50',
),
);
$result = array();
foreach($data as $key => $values)
{
foreach($values as $number => $value)
$result[$number][$key] = $value;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)

I think this will do the job for you, though I don't have a good data set to test against.
$wanted_array = array();
// Iterate over the outer array to get the text keys & inner arrays
foreach ($current_array as $txtkey=>$arr) {
// Iterate over each inner array to get the numeric key
foreach ($arr as $numkey=>$val) {
// Set a numeric key pointing to a new array
// onto the new outer array if it isn't already there
if (!isset($wanted_array[$numkey])) $wanted_array[$numkey] = array();
// Swap the keys of the outer and inner arrays.
$wanted_array[$numkey][$txtkey] = $val;
}
}
Update: Using test array from #hakre's answer, here it is in practice:
$current_array = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865'
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3'
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50'
)
);
// Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)

Like you said, just loop through it to build it.
$wanted = array();
foreach($current['item_id'] as $key => $value) {
$wanted[$key] = array(
'qty' = $current['qty'][$key],
'item_id' = $current['item_id'][$key],
'item_name' = $current['item_name'][$key],
'price' = $current['price'][$key]
);
}
print_r($wanted);

You can loop over your original array using the foreach loop, which gives you the $key, and $value for each item in your array. From there, construct your new array as you like.
$array2 = array();
foreach ($array1 as $key => $value)
{
$array2[] = array('key' => 'value');
}

Related

sum array indexes with same value for a specific key

I have the following array:
[0] => Array
(
[id] => 1
[uid] => 50
[sum1] => 1
[sum2] => 2
)
[1] => Array
(
[id] => 2
[uid] => 50
[sum1] => 2
[sum2] => 4
)
[2] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
As you can see, on some of those indexes, [uid] is the same. The length and data of the array is dynamic.
what i need to do is merge the indexes that have the same value for[uid] and sum the values for the other keys:
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
But for the life of me, i can't figure out how to do that.
Any help appreciated!
You can do it like this way,
<?php
$mainArray = [
0 => Array
(
'id' => 1,
'uid' => 50,
'sum1' => 1,
'sum2' => 2
),
1 => Array
(
'id' => 2,
'uid' => 50,
'sum1' => 2,
'sum2' => 4
),
2 => Array
(
'id' => 3,
'uid' => 51,
'sum1' => 3,
'sum2' => 5
)
];
$newArray=[];
foreach ($mainArray as $value) {
if(!array_key_exists($value['uid'], $newArray)){
// Store first time
$newArray[$value['uid']] = $value;
}else{
// Already exist, then sum and replace it
$newArray[$value['uid']]['id'] = $value['id'];
$newArray[$value['uid']]['sum1'] += $value['sum1'];// Sum with previous value
$newArray[$value['uid']]['sum2'] += $value['sum2'];// Sum with previous value
}
}
$newArray = array_values($newArray);// Reset indexes, Start the array index with zero
print_r($newArray);// To see the output
Output:
Array
(
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
)
I think you are correct. Actually, i solved the problem using something similar:
$sumArray = Array();
foreach ($array1 as $item){
if(isset($sumArray[$item['uid']])){
$sumArray[$item['idPartener']]['sum1'] += $item['sum1'];
$sumArray[$item['idPartener']]['sum2'] += $item['sum2'];
}else{
$sumArray[$item['uid']] = Array(
'id' => $item['id'],
'sum1' => $item['sum1'],
'sum2' => $item['sum2'] ,
);
}
}
Thanks all for your help!

Removing first array of multidimensional array

I want to remove the first.. how to say that outside of the array and left inside array of a multidimension array. I couldn't found out the solution.. someone knows how to do it??
This is my code. I assign a array and i try to put into another array like this.
$final_sku = array();
foreach($skus as $sku){
foreach($sku as $key => $s){
$final_sku[] = array('Sku' => $s);
}
}
$newArray = array(
"Product" => array(
"PrimaryCategory" => "1",
"AssociatedSku" => "12",
"Attributes" => array(
),
"Skus" => $final_sku
)
);
And this is the $final_sku output be like.
[0] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
)
[1] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
)
I want the output be like this.
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
UPDATE: I want to pass the array and convert to xml. So the array key would be duplicated.
It does not make sense to have the same array of 2 members under the same key.
If you want to access one of them, what will be its uniqueness over the other?
The logical solution is
[sku] => [
0 => [first sku data....],
1 => [sku data....],
]

I want to get the duplicate tag_name arrays to group under one array

From this below array:
Array
(
[0] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.05
[total_marks] => 2.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 52
)
[1] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.10
[total_marks] => 4.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 28
)
[2] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 0.20
[total_marks] => 1.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 20
)
[3] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.00
[total_marks] => 6.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 17
)
[4] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.50
[total_marks] => 6.00
[student_count] => 1
[level] => Hard
[overall_percentage] => 25
)
)
To some thing similar: As i need an array based on tag name with its all levels inside that array so that I can get the individual tag name with its level and percentage for further calculations
[tag_name]
{
[level]:[overall_percentage]
[level]:[overall_percentage]
.
.
}
.
.
.
$newArray = array();
foreach($yourarray as $item){
$newArray[$item['tag_name']][$item['level']] = $item['overall_percentage'];
}
This will add create a $newArray as follows:
Array(
'tag_name' => Array(
'Medium' => '27'
)
)
try this code
$array =array
(
'0' => array
(
'tag_name' => 'Quant-Arithmetic',
'student_marks' => ' 1.05',
'total_marks' => ' 2.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 52',
),
'1' => array
(
'tag_name' => ' Quant-Arithmetic',
'student_marks' => ' 1.10',
'total_marks' => ' 4.00',
'student_count' => ' 1',
'level' => ' Medium',
'overall_percentage' => ' 28',
),
'2' => array
(
'tag_name' => ' Quant-Algebra',
'student_marks' => ' 0.20',
'total_marks' => ' 1.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 20',
)
);
// declare a new array
$new_array = array();
foreach($array as $values){
// trim array elements
$trimmed_array=array_map('trim',$values);
if(isset($new_array[$trimmed_array['tag_name']])){
//add elements to array
$new_array[$trimmed_array['tag_name']][$trimmed_array['level']] = $trimmed_array['overall_percentage'];
}else{
// create new array
$new_array[$trimmed_array['tag_name']] = array($trimmed_array['level'] => $trimmed_array['overall_percentage']);
}
}
// php array
print_r($new_array);
// json
echo json_encode($new_array);
Out Put : array
Array
(
[Quant-Arithmetic] => Array
(
[Easy] => 52
[Medium] => 28
)
[Quant-Algebra] => Array
(
[Easy] => 20
)
)
Out Put : Json
{"Quant-Arithmetic":{"Easy":"52","Medium":"28"},"Quant-Algebra":{"Easy":"20"}}

unique array on base on value of specific key

I have the following array:
Array
(
[0] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 2
)
[1] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 3
)
[2] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 4
)
[3] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 23
)
[4] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 24
)
)
I have two different hotelID keys. I would like to extract only one element (the first one) where the hotelID is unique in whole array. I am trying with following code:
$data['uniqueHotels'] = array_map('unserialize', array_unique(array_map('serialize', $hotels)));
but without any luck so far.
Anyone can give me a hint?
If looking for the first element:
<?php
$hotels = array(
array(
'id' => 1,
'hotelID' => 10
),
array(
'id' => 2,
'hotelID' => 10,
),
array(
'id' => 3,
'hotelID' => 20,
),
array(
'id' => 4,
'hotelID' => 20,
),
);
function getUniqueHotels($hotels) {
$uniqueHotels = array();
foreach($hotels as $hotel) {
$niddle = $hotel['hotelID'];
if(array_key_exists($niddle, $uniqueHotels)) continue;
$uniqueHotels[$niddle] = $hotel;
}
return $uniqueHotels;
}
$unique_hotels = getUniqueHotels($hotels);
print_r($unique_hotels);
results in:
Array
(
[10] => Array
(
[id] => 1
[hotelID] => 10
)
[20] => Array
(
[id] => 3
[hotelID] => 20
)
)
You could simply loop through the array and add them to a new array, indexed by hotelID. This way any duplicates will just overwrite the existing value and you end up with one entry per hotel:
$unique = array();
foreach ($hotels as $value)
{
$unique[$value['hotelID']] = $value;
}
$data['uniqueHotels'] = array_values($unique);
Here is a dynmaic solution:
function uniqueAssocArray($array, $uniqueKey){
$unique = array();
foreach ($array as $value){
$unique[$value[$uniqueKey]] = $value;
}
$data = array_values($unique);
return $data;
}
How to use:
uniqueAssocArray($yourArray, 'theKey');
along the lines of what you're trying,
array_unique(array_map(function($hotel) { return $hotel['hotelID']; }, $array))

Create new array depending on key

My array is like that:
Array
(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
)
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
[2] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[3] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
I want to change that array like that depending on key['type']. If array key['type'] are same, I want to change array like that:
Array
(
[car] => Array(
[0]=>Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
),
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
),
[train]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[cruise]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
)
)
what I mean is that if key['type'] is car, I want to create car array or if the type is train I want to create train array or if the type is cruise I want to create cruise array. I don't know how to loop the array. Anyone please help me. Thanks a lot!
Here's a simple way to do it: loop over the data, and just append to the subarray matching the type value:
// starting data
$starting_array = array (
0 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 1,
'tran_name' => 'private',
'tran_image' => '1251961905A1.jpg',
'type' => 'car',
'troute_id' => 10
),
1 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 2,
'tran_name' => 'express',
'tran_image' => 'bus3.jpg',
'type' => 'car',
'troute_id' => 13
),
2 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 3,
'tran_name' => 'MyanmarTrain',
'tran_image' => 'Burma-Gorteikviaduct.jpg',
'type' => 'train',
'troute_id' => 16
),
3 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 4,
'tran_name' => 'Ayeyarwaddy Cruise',
'tran_image' => 'boat-ChutzpahToo1.jpg',
'type' => 'cruise',
'troute_id' => 22
)
);
// initialize the result array
$result = array();
// loop over the starting array
foreach($starting_array as $entry) {
// make sure the result array has a key matching this item's type
if(!array_key_exists($entry['type'], $result)) {
$result[ $entry['type'] ] = array();
}
// add this item to the result array
$result[ $entry['type'] ][] = $entry;
}
// this is just for testing, so you can verify the output matches your desired result
echo "<pre>";
var_dump($result);
echo "</pre>";
Try this:
<?php
$tempArr = Array
(
Array(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 1,
"tran_name" => "private",
"tran_image" => "1251961905A1.jpg",
"type" => "car",
"troute_id" => 10
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 2,
"tran_name" => "express",
"tran_image" => "bus3.jpg",
"type" => "car",
"troute_id" => 13
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 3,
"tran_name" => "MyanmarTrain",
"tran_image" => "Burma-Gorteikviaduct.jpg",
"type" => "train",
"troute_id" => 16
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 4,
"tran_name" => "Ayeyarwaddy Cruise",
"tran_image" => "boat-ChutzpahToo1.jpg",
"type" => "cruise",
"troute_id" => 22
)
);
$resultArr = array();
foreach($tempArr as $tempKey=>$temp)
{
if(!array_key_exists($temp['type'], $resultArr))
{
$resultArr[$temp['type']] = array();
}
$resultArr[$temp['type']][] = $temp;
}
echo '<pre>';
print_r($resultArr);
?>
This is working fine .....

Categories