Two-dimensional array to multidimensional array - php

This is what I have:
[courses] => array
(
array([id]=>1,[name]=>"course_1",[age]=>16,[location]=>"Berlin"),
array([id]=>2,[name]=>"course_1",[age]=>18,[location]=>"Berlin"),
array([id]=>3,[name]=>"course_1",[age]=>20,[location]=>"Berlin"),
array([id]=>4,[name]=>"course_1",[age]=>16,[location]=>"London"),
array([id]=>5,[name]=>"course_1",[age]=>18,[location]=>"Rome"),
array([id]=>6,[name]=>"course_2",[age]=>16,[location]=>"Berlin")
);
What I need is to transform this into a multidimensional array like this:
- each name can have multiple ages
- each age can have multiple locations
- id is not needed
So the new transformed array should have courses that have multiple ages that have multiple locations.
I first tried to create an array for each key:
// all courses, sorted, once
$x = 0;
$course_names = array();
foreach ($courses as $item) {
$course_names[$x] = $item['name'];
$x++;
}
$course_names = array_unique($course_names);
sort($course_names);
// all ages, sorted, once
$x = 0;
$ages = array();
foreach ($courses as $item) {
$ages[$x] = $item['age'];
$x++;
}
$ages = array_unique($ages);
sort($ages);
// all locations, sorted, once
$x = 0;
$locations = array();
foreach ($courses as $item) {
$locations[$x] = $item['location'];
$x++;
}
$location = array_unique($location);
sort($location);
Then I tried to create another array as requested (don't swear at me, is one of many tries):
$counter = 0;
foreach ($location as $loc_key=>$loc_val) {
foreach ($ages as $age_key=>$age_val) {
foreach ($course_names as $cou_key=>$cou_val) {
foreach ($courses as $course) {
if ($course['name']==$cou_val) {
if ($course['age']==$age_val) {
if ($course['location']==$loc_val) {
$final_json[$counter]['ages']['locations'][] = $loc_val;
}
$final_json[$counter]['ages'][] = $age_val;
}
$final_json[$counter]['id'] = $course['id'];
$final_json[$counter]['name'] = $cou_val;
$counter++;
}
}
}
}
}
The resulted array should be something like this:
[courses] => array
(
[0] => array
(
[name] => "course_1",
[ages] => array
(
[0] => array
(
[age] => 16,
[locations] => array ([0]=>"Berlin",[1]=>"London")
),
[1] => array
(
[age] => 18,
[locations] => array ([0]=>"Berlin",[1]=>"Rome")
),
[2] => array
(
[age] => 20,
[locations] => array ([0]=>"Berlin")
)
)
)
[1] => array
(
[name] => "course_2",
[ages] => array
(
[0] => array
(
[age] => 16,
[locations] => array ([0]=>"Berlin")
)
)
)
);
I'm fighting with this for some time, I feel blocked, any idea is more than welcomed.

$courses = array(
array("id"=>1,"name"=>"course_1","age"=>16,"location"=>"Berlin"),
array("id"=>2,"name"=>"course_1","age"=>18,"location"=>"Berlin"),
array("id"=>3,"name"=>"course_1","age"=>20,"location"=>"Berlin"),
array("id"=>4,"name"=>"course_1","age"=>16,"location"=>"London"),
array("id"=>5,"name"=>"course_1","age"=>18,"location"=>"Rome"),
array("id"=>6,"name"=>"course_2","age"=>16,"location"=>"Berlin"),
);
foreach ($courses as $item) {
$course_age[] = $item['age'];
$course_names[] = $item['name'];
$course_location[] = $item['location'];
}
$course_age = array_unique($course_age);
$course_names = array_unique($course_names);
$course_location = array_unique($course_location);
$finalArray = array();
$finalArrayKey=0;
foreach ($course_names as $key => $courseValue) {
foreach ($courses as $key => $actualValue) {
if($actualValue['name']==$courseValue){
$finalArray[$finalArrayKey]['name'] = $courseValue;
$finalArray[$finalArrayKey]['ages'] = array();
$finalArray[$finalArrayKey]['ages']['location'] = array();
}
}
foreach ($courses as $key => $actualValue) {
if($actualValue['name']==$courseValue){
if(!in_array($actualValue['age'], $finalArray[$finalArrayKey]['ages']))
$finalArray[$finalArrayKey]['ages'][] = $actualValue['age'];
if(!in_array($actualValue['location'], $finalArray[$finalArrayKey]['ages']['location']))
$finalArray[$finalArrayKey]['ages']['location'][] = $actualValue['location'];
}
}
++$finalArrayKey;
}
echo "<pre>";
print_r($finalArray);
Sample Output:
Array
(
[0] => Array
(
[name] => course_1
[ages] => Array
(
[location] => Array
(
[0] => Berlin
[1] => London
[2] => Rome
)
[0] => 16
[1] => 18
[2] => 20
)
)
[1] => Array
(
[name] => course_2
[ages] => Array
(
[location] => Array
(
[0] => Berlin
)
[0] => 16
)
)
)

For simplicity sake decided to modify the output of the finalArray.
The new finalArray would look like this:
Array
(
[course_1] => Array
(
[ages] => Array
(
[16] => Array
(
[locations] => Array
(
[0] => Berlin
[1] => London
)
),
[18] => Array
(
[locations] => Array
(
[0] => Berlin
[1] => Rome
)
),
[20] => Array
(
[locations] => Array
(
[0] => Berlin
)
)
)
),
[course_2] => Array
(
[ages] => Array
(
[16] => Array
(
[locations] => Array
(
[0] => Berlin
)
)
)
)
)
This is the code:
foreach ($courses as $item) {
$course_names[] = $item['name'];
}
$course_names = array_unique($course_names);
sort($course_names);
$finalArray = array();
foreach ($course_names as $key => $courseValue) {
foreach ($courses as $key => $actualValue) {
if($actualValue['name']==$courseValue) {
$finalArray[$courseValue] = array();
$finalArray[$courseValue]['id'] = $actualValue['id'];
$finalArray[$courseValue]['ages'] = array();
}
}
foreach ($courses as $key => $actualValue) {
if($actualValue['name']==$courseValue) {
if(!array_key_exists($actualValue['age'],$finalArray[$courseValue]['ages'])) {
$finalArray[$courseValue]['ages'][$actualValue['age']] = array ();
}
}
}
}
foreach ($finalArray as $course_name=>$arr) {
foreach ($arr['ages'] as $age=>$arr2) {
foreach($courses as $item) {
if($item['name'] == $course_name && $item['age'] == $age && !in_array($item['location'], $finalArray[$course_name]['ages'][$age]['locations'])) {
$finalArray[$course_name]['ages'][$age]['locations'][] = $item['location'];
}
}
}
}

Not sure exactly what format you're looking for, but have a look at this:
$courses = array
(
array('id'=>1, 'name' =>"course_1",'age'=>16,'location'=>"Berlin"),
array('id'=>2,'name'=>"course_1",'age'=>18,'location'=>"Berlin"),
array('id'=>3,'name'=>"course_1",'age'=>20,'location'=>"Berlin"),
array('id'=>4,'name'=>"course_1",'age'=>16,'location'=>"London"),
array('id'=>5,'name'=>"course_1",'age'=>18,'location'=>"Rome"),
array('id'=>6,'name'=>"course_2",'age'=>16,'location'=>"Berlin")
);
$newCourses = [];
foreach ($courses as $item){
$newCourses[$item['name']]['ages'][$item['age']]['locations'][] = $item['location'];
}
$newCourses will be:
array (
'course_1' =>
array (
'ages' =>
array (
16 =>
array (
'locations' =>
array (
0 => 'Berlin',
1 => 'London',
),
),
18 =>
array (
'locations' =>
array (
0 => 'Berlin',
1 => 'Rome',
),
),
20 =>
array (
'locations' =>
array (
0 => 'Berlin',
),
),
),
),
'course_2' =>
array (
'ages' =>
array (
16 =>
array (
'locations' =>
array (
0 => 'Berlin',
),
),
),
),
)
Even if this isn't the format you're after you could probably play with it to get it how you want.

Related

Retrieve nested array key

I'm going crazy with this.
So, let's say I got this array:
Array
(
[0] => Array
(
[variation_name] => variation_1
[license_type] => Array
(
[slug] => license_x
[price] => price_x
[dimensions] => dimensions_x
)
)
[1] => Array
(
[variation_name] => variation_2
[license_type] => Array
(
[slug] => license_y
[price] => price_y
[dimensions] => dimensions_y
)
)
[2] => Array
(
[variation_name] => variation_3
[license_type] => Array
(
[slug] => license_solid_z
[price] => price_z
[dimensions] => dimensions_z
)
)
)
and I want to echo the array values beginning with "license_solid" and the value of the array that contains it.
To have the "license_solid" entries I run the following:
$attribute_pa_licenses = array_column($array, 'license_type');
$attribute_pa_license_slug = array_column($attribute_pa_licenses, 'slug');
foreach ($attribute_pa_license_slug as $value) {
if (0 === strpos($value, 'license_solid')) {
echo $value;
}
}
and it DO works, but I'm not understanding how to echo also the array "containing" $value
in this example it should give variation_3
Rewrite your foreach loop as below:-
foreach ($attribute_pa_license_slug as $value) {
if(!empty($value['license_type']['slug'])){
$slug = $value['license_type']['slug'];
if (strpos($slug, 'license_solid') !== false) {
echo $slug; // echo your matched value
$data[] = $value; // store your array in data array
}
}
}
print_r($data); // print arrays who has valid slug values
Traditional foreach is good for array which structure is known but for large array with unknown structure array iterator is good.
have a look on below two methods
<?php
$array = Array
(
'0' => Array
(
'variation_name' => 'variation_1',
'license_type' => Array
(
'slug' => 'license_x',
'price' => 'price_x',
'dimensions' => 'dimensions_x'
)
),
'1' => Array
(
'variation_name' => 'variation_2',
'license_type' => Array
(
'slug' => 'license_y',
'price' => 'price_y',
'dimensions' => 'dimensions_y'
)
),
'2' => Array
(
'variation_name' => 'variation_3',
'license_type' => Array
(
'slug' => 'license_solid_z',
'price' => 'price_z',
'dimensions' => 'dimensions_z'
)
)
);
//METHOD 1 - For known structured array
foreach($array AS $key => $val) {
$slug = $val['license_type']['slug'];
if (strpos($slug, 'license_solid') !== false) {
$data[] = $array[$key];
}
}
print_r($data);
//METHOD 2 - For unknown structured array (use iterator for unknow and large structured)
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$data = array();
foreach ($it as $key => $val) {
$ar = $it->getSubIterator($it->getDepth() - 1);
if($key == 'slug' && strpos($val, 'license_solid') !== false){
$data[] = (array) $ar;
}
}
print_r($data);
Output:
Array
(
[0] => Array
(
[variation_name] => variation_3
[license_type] => Array
(
[slug] => license_solid_z
[price] => price_z
[dimensions] => dimensions_z
)
)
)
Use foreach over whole array with $key argument:
foreach ($array as $key => $value) {
$slugValue = $value['license_type']['slug'];
if (...) { echo $slugValue; }
// $key contains current array index (0..2 for array in example)
// $value contains array with variation_name, license_type
}

Create 2 dimensional array from 1 dimensional

How from this array:
Array
(
[0] => Array
(
[BLACK] => Array
(
[0] => 3171
[1] => 3173
[2] => 3175
)
[WHITE] => Array
(
[0] => 3170
[1] => 3172
[2] => 3174
)
)
[1] => Array
(
[SMALL] => Array
(
[0] => 3170
[1] => 3171
)
[MEDIUM] => Array
(
[0] => 3172
[1] => 3173
)
[LARGE] => Array
(
[0] => 3174
[1] => 3175
)
)
)
I could create something like this:
$array['BLACK']['SMALL'] = 3171;
$array['BLACK']['MEDIUM'] = 3173;
$array['BLACK']['LARGE'] = 3175;
$array['WHITE']['SMALL'] = 3170;
$array['WHITE']['MEDIUM'] = 3172;
$array['WHITE']['LARGE'] = 3174;
so create 2 dimensional array from 1 dimensional, where option is same.
<?php
$colors = array('BLACK' => array('3171','3173','3175'),'WHITE' => array('3170','3172','3174'));
$sizes = array('SMALL' => array('3170','3171'),'MEDIUM' => array('3172','3173'), 'LARGE' => array('3174','3175'));
$merged = array();
foreach ($colors as $c_key => $color) {
foreach ($color as $c_val) {
foreach ($sizes as $s_key => $size) {
foreach ($size as $s_val) {
if ($c_val == $s_val) {
$merged[$c_key][$s_key] = $c_val;
}
}
}
}
}
// var_dump($merged);
?>

how to get array from get to normal array in php

I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)

Array values update

I have an array like this..
Array
(
[0] => Array
(
[0] => 1``
[1] => 2``
[2] => 3``
)
[1] => Array
(
[0] => 4``
[1] => 5``
[2] => 6``
)
[2] => Array
(
[0] =>
[1] => 7``
[2] =>
)
)
I want the result like this below,
$remaining_value = Array
(
[0] => 1`` 4``,
[1] => 2`` 5`` 7``,
[2] => 3`` 6``,
)
How to do this in an single loop.. Plz help me..
If the lower-level arrays will always have the same number of elements then you can do something like this:
$subArrayCount = count( $inputArray );
$outputArray = array();
$firstSubArray = reset( $inputArray );
foreach( $firstSubArray as $key => $value )
{
$outputArray[$key] = $value;
for( $innerLoop = 1; $innerLoop < $subArrayCount; $innerLoop++ )
{
$outputArray[$key].= $inputArray[$innerLoop][$key];
}
}
var_dump( $outputArray );
This should work:
<?php
$remaining_value=array();
foreach($array as $loopv1){
foreach($loopv1 as $key2 => $loopv2){
if(empty($remaining_value[$key2]))$remaining_value[$key2]=$loopv2; else $remaining_value[$key2].=" ".$loopv2;
}
}
?>

PHP array - create an array from an array?

Hello I have POST array that looks like this,
Array (
[email_address] => Array (
[0] => simon#simonainley.info
[1] => simon2#simonainley.info
)
[firstname] => Array (
[0] => Simon
[1] => Simon2
)
[surname] => Array (
[0] => Ainley
[1] => Ainley2
)
[companies_company_id] => NULL,
[save_user] => Save User
)
I wanting to create an new array where I would get the first email_address, firstname, and surname into an array, deal with that data and then proceed to the next email-address, firstname and surname.
Is this possible? I have tried this code,
$newArray = array();
foreach($_POST as $key => $value) {
$newArray[] = $value;
}
however that code just produces this,
Array (
[0] => Array (
[0] => simon#simonainley.info
[1] => simon2#simonainley.info
)
[1] => Array (
[0] => Simon
[1] => Simon2
) [2] => Array ( [0] => Ainley [1] => Ainley2 ) [3] => [4] => Save User ) 1
What do I need to do?
$count = count($_POST['firstname']);
$result = array();
for ($i = 0; $i <= $count; $i ++) {
$result[] = array(
'email_address' => $_POST['email_address'][0],
'firstname' => $_POST['firstname'][0],
'lastname' => $_POST['lastname'][0]
);
}
or (if the numeric indices have any meaning)
$result = array();
foreach (array_keys($_POST['email_address']) as $index) {
$result[$index] = array(
'email_address' => $_POST['email_address'][$index],
'firstname' => $_POST['firstname'][$index],
'lastname' => $_POST['lastname'][$index]
);
}
You could try:
foreach($_POST as $key=>$value)
{
$count=0;
foreach($value as $val)
{
$newArray[$count++]=Array($key=>$val);
}
}
You only need to re-order the elements into the $_POST array:
$users = array();
foreach($_POST as $key => $values) {
if (is_array($values)) {
foreach($values as $index => $value) {
$users[$index][$key] = $value;
}
}
}
With the data you provided, it will give you this in the $users array:
[0] => Array
(
[email_address] => simon#simonainley.info
[firstname] => Simon
[surname] => Ainley
)
[1] => Array
(
[email_address] => simon2#simonainley.info
[firstname] => Simon2
[surname] => Ainley2
)
Elements in $_POST that are not an array are ignored and filtered out.

Categories