PHP group multidimensional array by repeated values - php

I have a simple two dimensional array like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John
[company] => One
[price] => 12.22
)
[1] => Array
(
[id] => 1
[name] => John
[company] => Two
[price] => 14.33
)
[2] => Array
(
[id] => 2
[name] => Mike
[company] => One
[price] => 15.11
)
[3] => Array
(
[id] => 2
[name] => Mike
[company] => Two
[price] => 10.12
)
[4] => Array
(
[id] => 3
[name] => Paul
[company] => One
[price] => 42.22
)
[5] => Array
(
[id] => 3
[name] => Paul
[company] => Two
[price] => 56.62
)
[6] => Array
(
[id] => 3
[name] => Paul
[company] => Three
[price] => 16.12
)
)
I need to group id and name, then create an array with different values something like this:
Array
(
[0] => Array
(
[id] => 1
[name] => John
[companies] => array (
array(
[company] => One
[price] => 12.22
)
array(
[company] => Two
[price] => 14.33
)
)
)
[1] => Array
(
[id] => 2
[name] => Mike
[companies] => array (
array(
[company] => One
[price] => 15.11
)
array(
[company] => Two
[price] => 10.12
)
)
)
[2] => Array
(
[id] => 3
[name] => Paul
[companies] => array (
array(
[company] => One
[price] => 42.22
)
array(
[company] => Two
[price] => 56.62
)
array(
[company] => Three
[price] => 16.12
)
)
)
)
What is the best way to do it with PHP?
This is my attemp:
<?php
$items=array();
$temp = 0;
$companies = array('uno','dos','tres');
foreach ($values as $value) {
if ($temp == $value['id'] )
continue;
else
$temp == $value['id'];
foreach ($companies as $key => $company){
foreach ($values as $item){
if ($item['id'] == $temp && $item['company'] == $key)
$value['company'][$key] = $item['price'];
}
}
$items[] = $value;
}

Use the id as the key for the new array, then just append a new array with the next company and price
foreach($array as $v) {
$result[$v['id']]['id'] = $v['id'];
$result[$v['id']]['name'] = $v['name'];
$result[$v['id']]['companies'][] = array('company' => $v['company'],
'price' => $v['price']);
}
If you need to re-index it (probably not):
$result = array_values($result);

Related

Making a nested array in php

Probably my question is too much common or easy for you, but I really have no idea how to do it. Trying all everything I know and lots of googling didn't help me.
I just need a nested array.
Here is my PHP code:
EDITED
Corrected: $data['product_names'][$language['language_id']][] = array(
$data['product_names'] = array();
foreach ($data['languages'] as $language) {
$product_names_info = $this->model_catalog_category->getCategoryMultiLang($this->request->get['product_id'], $language['language_id']);
if ($product_names_info) {
$data['product_names'][$language['language_id']][] = array(
'category_id' => $product_names_info['category_id'],
'language_id' => $product_names_info['language_id'],
'name' => $product_names_info['name']
);
}
}
print_r($data['product_names']);
The result that I get:
Array
(
[5] => Array
(
[0] => Array
(
[category_id] =>
[language_id] =>
[name] =>
)
)
[2] => Array
(
[0] => Array
(
[category_id] =>
[language_id] =>
[name] =>
)
)
[4] => Array
(
[0] => Array
(
[category_id] =>
[language_id] =>
[name] =>
)
)
...
The result should look like this:
Array
(
[0] => Array
(
[language_id] => 1
[category_id] => 8
[name] => book
)
[1] => Array
(
[language_id] => 5
[category_id] => 188
[name] => magazine
)
...
)
Array
(
[0] => Array
(
[language_id] => 1
[category_id] => 8
[name] => buch
)
...
UPDATED
The result of print_r($product_names_info); inside foreach ($data['languages'] as $key => $language) {
Array
(
[0] => Array
(
[language_id] => 5
[category_id] => 8
[name] => Gecelik
)
[1] => Array
(
[language_id] => 5
[category_id] => 188
[name] => Sabahlık
)
...
)
Array
(
[0] => Array
(
[language_id] => 2
[category_id] => 8
[name] => لباس خواب
)
[1] => Array
(
[language_id] => 2
[category_id] => 188
[name] => Sabahlık
)
Thanks for any kind help.
$data['product_names'] = array();
foreach ($data['languages'] as $language) {
$product_names_info = $this->model_catalog_category->getCategoryMultiLang($this->request->get['product_id'], $language['language_id']);
if ($product_names_info) {
foreach ($product_names_info as $key => $value) {
$data['product_names'][$language['language_id']][] = array(
'category_id' => $value['category_id'],
'language_id' => $value['language_id'],
'name' => $value['name'],
);
}
}
}
print_r($data['product_names']);
I think you were missing foreach for the data you fetched into var $product_names_info

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("----------------------------")

Create associative array with value as key

I have this array with information, which I want to create a new associative array with. Each key in the associative array should be the "name" from the old one. And in each new key, I want the corresponding information to be collected.
Array
(
[0] => Array
(
[id] => 1
[counter] => 21478813
[serie] => 2607171234
[name] => Ben
)
[1] => Array
(
[id] => 2
[counter] => 21478858
[serie] => 2607177151
[name] => Evan
)
[2] => Array
(
[id] => 3
[counter] => 21478817
[serie] => 2607171341
[name] => Steve
)
[3] => Array
(
[id] => 4
[counter] => 21471798
[serie] => 2607178561
[name] => Ben
)
[4] => Array
(
[id] => 5
[counter] => 21478811
[serie] => 2607171347
[name] => Ben
)
)
This is the array I'm trying to create:
Array
(
["Ben"] => Array
(
[0] => Array
(
[id] => 1
[counter] => 21478813
[serie] => 2607171234
[name] => Ben
)
[1] => Array
(
[id] => 4
[counter] => 21471798
[serie] => 2607178561
[name] => Ben
)
[2] => Array
(
[id] => 5
[counter] => 21478811
[serie] => 2607171347
[name] => Ben
)
)
["Evan"] => Array
(
[0] => Array
(
[id] => 2
[counter] => 21478858
[serie] => 2607177151
[name] => Evan
)
)
["Steve"] => Array
(
[0] => Array
(
[id] => 3
[counter] => 21478817
[serie] => 2607171341
[name] => Steve
)
)
)
$newArr = array();
foreach($myArr as $value) {
$name = $value['name'];
if (isset($newArr[$name])) {
$newArr[$name][] = $value;
}
else {
$newArr[$name] = array($value);
}
}
Use a foreach loop to create a new array:
$newArr = [];
foreach($myArr as $key => $value){
$newArr[$myArr[$key][$value['name']]][] = $myArr[$key];
}

fill an array with missing values and keys

I have this array $all_zones that comes sometimes with missing keys and values and I would like to fill the array with empty values for the messing keys, here's the array:
Array
(
[0] => Array
(
[id_zone] => 1
[name] => Europe
[price] => Array
(
[0] => 3.00
[1] => 6.00
)
[id_delivery] => Array
(
[0] => 1
[1] => 2
)
)
[1] => Array
(
[id_zone] => 3
[name] => Asia
)
[2] => Array
(
[id_zone] => 4
[name] => Africa
[price] => Array
(
[0] => 3.00
[1] => 6.00
)
[id_delivery] => Array
(
[0] => 3
[1] => 4
)
)
[3] => Array
(
[id_zone] => 5
[name] => Oceania
)
)
The thing is the $all_zones[$key]['price'] depend on how many ranges there's for each Zone, inthis case $range_count = count($all_ranges); will display 2, so I'd like to fill the missing keys for 2 times : Here's the output:
Array
(
[0] => Array
(
[id_zone] => 1
[name] => Europe
[price] => Array
(
[0] => 3.00
[1] => 6.00
)
[id_delivery] => Array
(
[0] => 1
[1] => 2
)
)
[1] => Array
(
[id_zone] => 3
[name] => Asia
[price] => Array
(
[0] =>
[1] =>
)
[id_delivery] => Array
(
[0] =>
[1] =>
)
)
[2] => Array
(
[id_zone] => 4
[name] => Africa
[price] => Array
(
[0] => 3.00
[1] => 6.00
)
[id_delivery] => Array
(
[0] => 3
[1] => 4
)
)
[3] => Array
(
[id_zone] => 5
[name] => Oceania
[price] => Array
(
[0] =>
[1] =>
)
[id_delivery] => Array
(
[0] =>
[1] =>
)
)
)
Here's what I've tried so far and didn't succeed:
$range_count = count($all_ranges);
$i=0;
foreach ($all_zones as $key => $value) {
if(isset($value['id_zone']) && isset($value['name']) && (!isset($value['price']) || !isset($value['id_delivery']))){
if($range_count>$i){
$disabled[]=$key;
$all_zones[$key]['price'][] = '';
$all_zones[$key]['id_delivery'][] = '';
}
$i++;
}
}
Any help with this? Much appreciated.
try this
$range_count = count($all_ranges);
foreach ($all_zones as $key => $value) {
if(isset($value['id_zone']) && isset($value['name']) && (!isset($value['price']) || !isset($value['id_delivery']))){
$disabled[]=$key;
if((!isset($value['price']))
{
for($i=0; $i<$range_count<$i++)
{
$all_zones[$key]['id_delivery'][] = '';
}
}
if((!isset($value['id_delivery']))
{
for($i=0; $i<$range_count<$i++)
{
$all_zones[$key]['id_delivery'][] = '';
}
}
}
}
You might have operator precedence problem.
( (!isset($value['price']) || !isset($value['id_delivery'])) )
The way to do this is to loop through the array, with an array_merge() on each array within the parent array to set your 'defaults'.
$zone_template = array(
'id_zone' => '',
'name' => '',
'price' => array(
0 => '',
1 => ''
),
'id_delivery' = array(
0 => '',
1 => ''
)
);
foreach ($all_zones as $zone) {
array_merge($zone_template, $zone);
}
Can also be done with array_walk()

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

Categories