How to create sub associative array? - php

I am learning associative arrays. This is what I am doing:
array_push( $classe ,array(
'year'=>$annoClasse,
'section'=>$sezione,
'student'=>$member->first_name." ".$member->last_name)
);
That creates:
array (
0 =>
array (
'year' => 'Secondo',
'section' => 'd',
'student' => 'Stephany Johnson',
),
1 =>
array (
'year' => 'Secondo',
'section' => 'd',
'student' => 'Sandra White',
),
)
How would I create something like this? Basically to have each separate property for the student.
array (
0 =>
array (
'year' => 'Second',
'section' => 'd',
'student' (
'name' => 'Stephany',
'surname' => 'Johnson'
)
),
1 =>
array (
'year' => 'Second',
'section' => 'd',
'student' (
'name' => 'Sandra',
'surname' => 'White'
),
)
)
And how would I then echo the student only?

This can be accomplished with the following code:
array_push( $classe ,array(
'year'=>$annoClasse,
'section'=>$sezione,
'student'=>array(
'name'=>$member->first_name,
'surname'=>$member->last_name
)
);
Then to echo only the student:
foreach ($classe as $c) {
echo $c['student']['name'] . " " . $c['student']['surname'] . PHP_EOL;
}

you can do it like that :
array_push( $classe ,array('year'=>$annoClasse, 'section'=>$sezione, 'student' => array('name' => $student_name, 'surname' => $student_surname)));
use foreach to loop the array and print the values you want :
foreach ($classe as $key => $value) {
echo $value['student']['name']; // or echo $value['student']['surname']; etc..
}

You can assign anything to the array key, it can be a bool, integer, string, or array. In your case just assign a new array to the student key.
array_push( $classe, array(
'year' => $annoClasse,
'section' => $sezione,
'student' => array(
'name' => $member->first_name,
'surname' => $member->last_name
)
));

Related

Create an array from an array based on value and include matches within as an array

I'm wanting to group my data by a specific value (parent name) and then merge all the items that share the same parent name under a "items" array
However it's overwriting the items array, not adding to it, so for example "items" in the output should have multiple items not just one.
Any ideas?
$result = array();
foreach ($page->products_codes as $option) {
$result[$option->parent->name]["title"] = $option->parent->title;
$result[$option->parent->name]["items"] = $option->title;
}
Outputs as:
array (
'fixture' =>
array (
'title' => 'Fixture',
'items' => 'Pinhole90 Fixed with LED51',
),
'finish' =>
array (
'title' => 'Finish',
'items' => 'RAL',
),
'ip-rating' =>
array (
'title' => 'IP Rating',
'items' => 'IP54',
),
'emergency' =>
array (
'title' => 'Emergency',
'items' => 'Maintained 3hr Self Test',
),
'installation' =>
array (
'title' => 'Installation',
'items' => 'Plaster-kit for seamless flush appearance',
),
'led' =>
array (
'title' => 'LED',
'items' => 'LED50 ONE',
),
'cct' =>
array (
'title' => 'CCT',
'items' => '90 CRI 4000K',
),
'beam-angle' =>
array (
'title' => 'Beam Angle',
'items' => '38°',
),
'protocol' =>
array (
'title' => 'Protocol',
'items' => 'Bluetooth',
),
'louvre-lens' =>
array (
'title' => 'Louvre/Lens',
'items' => 'Heavy Spread Lens',
),
)
Any thoughts?
Based on the preferred data structure you specified:
$result = array();
foreach ($page->products_codes as $option) {
$result[$option->parent->name]["title"] = $option->parent->title;
$result[$option->parent->name]["items"][] = $option;
}
$result = array_values($result);
Here's a working example: https://3v4l.org/u9XBk

How to fetch data into array 1 from array 2, based on particular key value?

I have two arrays.
$primary = array(
[0] => array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221',
'address' =>
),
[1] => array(
'name' => 'Meat Shop',
'place_id' => '1001',
'category' => '220,221'
'address' =>
),
[2] => array(
'name' => 'Bikini Shop',
'place_id' => '1010',
'category' => '100,102'
'address' =>
),
[3] => array(
'name' => 'Knife Shop',
'place_id' => '1012',
'category' => '1,3'
'address' =>
)
)
$moredata = array(
[0] => array(
'id' => '1000',
'category' => '900,901'
'address' => '35 Lawrence Park',
'phone' => '9000000099'
),
[1] => array(
'id' => '1001',
'category' => '909,300'
'address' => '39 Park Avenue',
),
[2] => array(
'id' => '1010',
'category' => '50,45'
'address' => '35 Trump Park',
'phone' => '8900000099'
)
)
I want to compare each data of $moredata with each data of $primary, and check if the place_id from $primary exists in $moredata. If it matches, then the corresponding records of that particular key will be updated. For example,
$newPrimary = array(
[0] => array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221,900,901',
'address' => '35 Lawrence Park',
'phone' => '9000000099'
),
[1] => array(
'name' => 'Meat Shop',
'place_id' => '220,221,1001',
'category' => '220,221,909,300',
'address' => '39 Park Avenue',
),
[2] => array(
'name' => 'Bikini Shop',
'place_id' => '1010',
'category' => '100,102,50,45'
'address' => '35 Trump Park',
'phone' => '8900000099'
),
[3] => array(
'name' => 'Knife Shop',
'place_id' => '1012',
'category' => '1,3'
'address' =>
)
)
place_id(1000) of primary matches with id(1000) of moredata, so the place_id(1000) of newPrimary is like this:-
array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221,900,901', // the categories get concated
'address' => '35 Lawrence Park',
'phone' => '9000000099'
)
However, for place_id(1001) of primary doesn't have phone field, so the id(1001) of newPrimary is like this:-
array(
'name' => 'Meat Shop',
'place_id' => '1001',
'category' => '220,221,909,300',
'address' => '39 Park Avenue',
)
place_id(1012) has no match, so it remains unchanged.
How can I create an array similar to newPrimary? It would be better if we can append the fields from moredata to the corresponding record from primary. I achieved the same using double foreach loop. I want to achieve this is a way to have lesser execution time.
foreach($primary as $key_fs => $prm)
{
foreach($moredata as $key_place => $pc)
{
if($prm['place_id'] == $pc['id'])
{
if(isset($pc['address']) && !empty($pc['address']))
$primary[$key_fs]['address'] = $pc['address'];
if(isset($pc['phone']) && !empty($pc['phone']))
$primary[$key_fs]['phone'] = $pc['phone'];
if(isset($pc['category']) && !empty($pc['category']))
$primary[$key_fs]['category'] .= ','.$pc['category'];
break;
}
}
}
Note:- The two arrays will have same dimension, but may not have same order.
You can use array_column to make the 2 arrays into multidimensional array. Use array_replace_recursive to merge the arrays.
You can use array_values if you want a simple array instead of multi dimensional output.
$primary = //Your array
$moredata = //Your array
$result = array_replace_recursive (array_column($primary, null, 'id') ,array_column($moredata, null, 'id') );
$result = array_values($result); //To convert the multidimensional array to simple array
Update:
You can use array_column to make a temp array for $moredata. This will make it easier to check if the id exist. Use the foreach to loop thru the array. If id exist on $moredata, simply concatenate the category.
$newMoreData = array_column($moredata, null, 'id');
$newPrimary = array();
foreach( $primary as $val ) {
if ( isset( $newMoreData[$val['place_id']] ) ) {
$temp = array_merge( $val, $newMoreData[$val['place_id']] );
$temp['category'] = $val['category'] . ',' . $newMoreData[$val['place_id']]['category'];
unset($temp['id']);
$newPrimary[] = $temp;
} else {
$newPrimary[] = $val;
}
}

merge two multi-dimensional arrays by key

How do I merge two multi-dimensional arrays using different keys that have matching values?
i.e. I want the data in arrayOne, 'Member'=> '45', to merge with the data in arrayTwo, 'id' => '45'.
I don't have access to the query, just the result array.
First Array:
arrayOne
array (
558 =>
array (
'id' => '558',
'Member' => '45',
'Status' => 'Active',
),
559 =>
array (
'id' => '559',
'Member' => '46',
'Status' => 'Active',
),
)
Second Array:
arrayTwo
array (
45 =>
array (
'id' => '45',
'Name' => 'Johnson',
),
46 =>
array (
'id' => '46',
'Name' => 'Smith',
),
)
Desired Array would be something like this:
arrayThree
array (
45 =>
array (
'id' => '45',
'Name' => 'Johnson',
'Member' => '45',
'Status' => 'Active',
),
46 =>
array (
'id' => '46',
'Name' => 'Smith',
'Member' => '46',
'Status' => 'Active',
),
)
This is the code I've most recently tried, which does merge the records, but it doesn't merge them by their matching values. Thank-you for any help!
function my_array_merge($arrayOne, $arrayTwo) {
$result = arrayThree();
foreach($arrayOne as $key => $value) {
$result[$key] = array_merge($value, $arrayTwo[$key]);
}
return $result;
}
echo "<pre>";
print_r($result);
echo "</pre>";
You can use array_map:
$array1 = array_combine(array_column($array1, 'Member'), $array1);
$result = array_map(function ($item2) use ($array1) {
$item1 = isset($array1[$item2['id']]) ? $array1[$item2['id']] : null;
if ($item2) {
$item2['Member'] = $item1['Member'];
$item2['Status'] = $item1['Status'];
}
return $item2;
}, $array2);
Here is working demo.

php loop over multidimensional array can combine same key/value into new array element

I am getting some data out of mysql into an array like this
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
[1] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
[2] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[3] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
what i need to do is for each row, if the key code appears more than once, merge the rows into one but create a new array for the other_value like so
array(
[0] = array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => array(
[0] => '555555',
[1] => '666666'
)
),
[1] = array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
[2] = array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
),
)
What is the best way to achieve this?
I did think about looping over the each row and checking for existence of thtat key/value then do something if it exists.
#AdRock i hope you want to merge array in case of when 'code' will be same, if this is so then try below one:
<?php
$arr = array(
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '555555'
),
array(
'code' => '123456',
'title' => 'something',
'price' => '2.00',
'other_value' => '666666'
),
array(
'code' => '234567',
'title' => 'something else',
'price' => '3.00',
'other_value' => '333333'
),
array(
'code' => '345678',
'title' => 'another thing',
'price' => '4.00',
'other_value' => NULL
)
);
echo "<pre>";
print_r($arr);// array before
$isExist = array();
foreach($arr as $key => $value){
if(in_array($value["code"], $isExist)){
$getKey = array_search($value["code"], $isExist);
$arr[$getKey]["other_value"] = array($arr[$getKey]["other_value"], $value["other_value"]);
unset($arr[$key]);
}
else{
$arr[$key] = $value;
}
$isExist[$key] = $value["code"];
}
echo "<pre>";
print_r(array_values($arr));// array after
?>
The approach that I would suggest is to loop through the array and store the value of code into a new array and store the entire result set into a new array. With each iteration, check whether the value is present or not in the code value stored array. And if value found then in that case, get the key of the code array and use the same key for the result array and store it inside the other_value. Hope it makes sense.
Looping over the array and creating a new array using the 'code' values as keys might be the simplest method. In that case you can check if the key allready exists.
$new_array=array();
foreach($array as $part){
$code_as_key = $part['code'];
//if code allready in the new array, just add a new value
if( isset($new_array[$code_as_key]) ){
$new_array[$code_as_key]['other_value'][] = $part['other_value'];
}
//else add the new code
else{
$new_array[$code_as_key]=$part;
}
}
//re-index the new array, starting from key 0
$new_array=array_values($new_array);

Remove Child Array If Value of A Key is Duplicate

I want to remove a child array from a multi-dimensional array in case a duplicate value found for a particular key. The answer(s) here didn't work at all. The answer here works, however, for large amount of arrays, that gets pretty slower. Looking for a cleaner and faster solution.
Example PHP Array
$args = array();
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 1',
),
'name' => 'Shortcode Name',
'action' => 'shortcodeaction',
'icon' => 'codeicon',
'image' => 'codeimage',
);
$args[] = array(
'section' => array(
'id' => 'section2',
'name' => 'Section 2',
),
'name' => 'Shortcode2 Name',
'action' => 'shortcodeaction2',
'icon' => 'codeicon2',
'image' => 'codeimage2',
);
$args[] = array(
'section' => array(
'id' => 'section3',
'name' => 'Section 3',
),
'name' => 'Shortcode3 Name',
'action' => 'shortcodeaction3',
'icon' => 'codeicon3',
'image' => 'codeimage3',
);
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 4',
),
'name' => 'Shortcode4 Name',
'action' => 'shortcodeaction4',
'icon' => 'codeicon4',
'image' => 'codeimage4',
);
$args[] = array(
'section' => array(
'id' => 'section5',
'name' => 'Section 5',
),
'name' => 'Shortcode5 Name',
'action' => 'shortcodeaction5',
'icon' => 'codeicon5',
'image' => 'codeimage5',
);
$sections = array();
foreach ( $args as $arg ) {
$sections[] = $arg['section'];
}
And, the print_r($sections) result.
Array
(
[0] => Array
(
[id] => section1
[name] => Section 1
)
[1] => Array
(
[id] => section2
[name] => Section 2
)
[2] => Array
(
[id] => section3
[name] => Section 3
)
[3] => Array
(
[id] => section1
[name] => Section 4
)
[4] => Array
(
[id] => section5
[name] => Section 5
)
)
Both Array[0] and Array[3] has the same value for the key id, therefor the entire Array[3] has to be removed in my case to avoid duplicates.
This is working for me though, but it gets really slow when there are 100s or more arrays.
$knownIds = array();
foreach( $sections AS $key=>$item ) {
if( array_key_exists($item['id'], $knownIds) === true ) {
unset( $sections[$key] );
} else {
$knownIds[$item['id']] = $key;
}
}
$sections = array_values($sections);
Tried several answers here in StackOverflow (including this), but none of them helped in my case.
Thanks
You can modify the whole using array_column and array_filter -
//get all the sections value
$section = array_column($args, 'section');
//store ids in temp array
$idArray = array_unique(array_column($section, 'id'));
//filter the array having unique id
$uniqueSections = array_filter($section, function ($key, $value) use ($idArray) {
return in_array($value, array_keys($idArray));
}, ARRAY_FILTER_USE_BOTH);
var_dump($uniqueSections);
For PHP <5.5
$section = array_map(function($args) {
return $args['section'];
}, $args);
$idArray = array_unique(array_map(function($section){return $section['id'];}, $section));

Categories