I have an associative multi dimensional array as below
$data = array();
$data = Array (
[0] => Array ( [class] => 1styear [branch] => IT [Exam] => SEM1 [student name] => Alex [Bio] => Good Boy )
[1] => Array ( [class] => 2ndyear [branch] => Finance [Exam] => SEM1 [student name] => Mark [Bio] => Intelligent )
[2] => Array ( [class] => 2ndyear [branch] => IT [Exam] => SEM1 [student name] => Shaun [Bio] => Football Player )
[3] => Array ( [class] => 1styear [branch] => Finance [Exam] => SEM2 [student name] => Mike [Bio] => Sport Player )
[4] => Array ( [class] => 1styear [branch] => IT [Exam] => SEM2 [student name] => Martin [Bio] => Smart )
[5] => Array ( [class] => 1styear [branch] => IT [Exam] => SEM1 [student name] => Philip [Bio] => Programmer )
)
I need to create new array based on similar element from above array. means I have to create array group. for e.g class element has repetitive 1styear and 2ndyear value. so it shouls create array of unique element. then again class is parent array and inside class array there should be branch based array and inside brance Exam array and inside Exam array there should be associative array of student name and bio.
so basically array should look like this
array(
"1styear" => array(
"IT" => array(
"SEM1" => array(
array(
"student name" => "Alex",
"Bio" => "Good Boy"
),
array(
"student name" => "Philip",
"Bio" => "Programmer"
)
),
"SEM2" => array(
array(
"student name" => "Martin",
"Bio" => "Smart"
)
)
)
),
"2ndyear" => array(
"Finance" => array(
"SEM1" => array(
array(
"student name" => "Mark",
"Bio" => "Intelligent"
)
),
"SEM2" => array(
array(
"student name" => "Mike",
"Bio" => "Sport Player"
)
)
)
)
);
To make group based on class i did like below which is working fine but how to create array inside that
$classgroup = array();
foreach($data as $inarray){
$classgroup[$inarray['class']][] = $inarray;
}
$classarray = array();
foreach($classgroup as $key => $value){
echo $key; // output is 1styear and secondyear
create array like above
}
---------------------------------EDIT----------------------------------
from the below loop
foreach($data as $array){
$grouped[$array["class"]][$array["branch"]][$array["Exam"]][]=array("student name"=>$array["student name"],"Bio"=>$array["Bio"]);
}
i got expected o/p
but if i need another o/p like this
expected o/p
array(
'1styear' =>
array (
0 =>
array(
'Exam' => 'SEM1',
'branch' =>
array (
0 => 'IT'
),
),
1 =>
array(
'Exam' => 'SEM2',
'branch' =>
array (
0 => 'IT'
),
),
),
'2ndyear' =>
array (
0 =>
array(
'Exam' => 'SEM1',
'branch' =>
array (
0 => 'Finance',
),
),
1 =>
array(
'Exam' => 'SEM2',
'branch' =>
array (
0 => 'Finance'
),
)
),
)
i tried following loop but not getting o/p as expected
foreach($data as $array){
$grouped[$array["class"]][]=array("Exam"=>$array["Exam"],"branch"=>$array["branch"]);
}
A one-liner in a loop!
foreach($data as $array){
$grouped[$array["class"]][$array["branch"]][$array["Exam"]][]=array("student name"=>$array["student name"],"Bio"=>$array["Bio"]);
}
$grouped produces:
Array(
[1styear] => Array(
[IT] => Array(
[SEM1] => array(
[0] => array(
[student name] => Alex,
[Bio] => Good Boy
),
[1] => array(
[student name] => Philip,
[Bio] => Programmer
)
),
[SEM2] => array(
[0] => array(
[student name] => Martin,
[Bio] => Smart
)
)
),
[Finance] => array(
[SEM2] => array(
[0] => array(
[student name] => Mike,
[Bio] => Sport Player
)
)
)
),
[2ndyear] => array(
[Finance] => array(
[SEM1] => array(
[0] => array(
[student name] => Mark,
[Bio] => Intelligent
)
)
),
[IT] => array(
[SEM1] => array(
[0] => array(
[student name] => Shaun,
[Bio] => Football Player
)
)
)
)
)
Your follow up case, was MUCH more fun/challenging. I had to knock the dust off of some functions I don't play with very often. Check this out:
<?php
$data = array (
array ( "class"=>"1styear","branch"=>"IT","Exam"=>"SEM1","student name"=>"Alex","Bio"=>"Good Boy"),
array ( "class"=>"2ndyear","branch"=>"Finance","Exam"=>"SEM1","student name"=>"Mark","Bio"=>"Intelligent" ),
array ( "class"=>"2ndyear", "branch"=>"IT","Exam"=>"SEM1","student name"=>"Shaun","Bio"=>"Football Player" ),
array ( "class"=>"1styear","branch"=>"Finance","Exam"=>"SEM2","student name"=>"Mike","Bio"=>"Sport Player" ),
array ( "class"=>"1styear","branch"=>"IT","Exam"=>"SEM2","student name"=>"Martin","Bio"=>"Smart"),
array ( "class"=>"1styear","branch"=>"IT","Exam"=>"SEM1","student name"=>"Philip","Bio"=>"Programmer" )
);
$class_keys=array_unique(array_column($data,"class")); // create array of unique class values
$Exam_keys=array_unique(array_column($data,"Exam")); // create array of unique Exam values
foreach($class_keys as $class_key){
$i=0; // "class" subarray index
foreach($Exam_keys as $Exam_key){
$q=array("class"=>$class_key,"Exam"=>$Exam_key); // this array can have 1 or more pairs
// create an array only of rows where $q's key-value pairs exist
$qualifying_array=array_filter(
$data,
function($val)use($q){
if(count(array_intersect_assoc($val,$q))==count($q)){ // total pairs found = total pairs sought
return $val;
}
},
ARRAY_FILTER_USE_BOTH
);
foreach($qualifying_array as $qa){ // push appropriate values into array
$grouped2[$class_key][$i]["Exam"]=$qa["Exam"];
$grouped2[$class_key][$i]["branch"][]=$qa["branch"];
}
if(isset($grouped2[$class_key][$i]["branch"])){ // ensure no duplicate values in "branch" subarray
$grouped2[$class_key][$i]["branch"]=array_unique($grouped2[$class_key][$i]["branch"]);
}
++$i; // increment the index for each "class" subarray
}
}
echo "<pre>";
print_r($grouped2);
echo "</pre>";
The output isn't identical to what you requested, but I think you were just showing what it should look like generally. If this isn't quite right, let me know.
array(
[1styear]=>array(
[0]=>array(
[Exam]=>SEM1
[branch]=>array(
[0]=>IT
)
),
[1]=>array(
[Exam]=>SEM2
[branch]=>array(
[0]=>Finance,
[1]=>IT
)
)
),
[2ndyear]=>array(
[0]=>array(
[Exam]=>SEM1
[branch]=>array(
[0]=>Finance,
[1]=>IT
)
)
)
)
Maybe something like this (not tested)?
$newData = [];
foreach ($data as $row) {
$student = [
'student name' => $row['student name'],
'Bio' => $row['Bio']
];
$newData[$row['class']][$row['branch']][$row['exam']][] = $student;
}
Related
Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);
I have this type of array
$arr = array(
0 => array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
)
1 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
How can I make all arrays as parallel arrays. So that all sub arrays are parallel to each other without using any loop.
Like this
$arr = array(
0 => array(
'name' => 'test1',
'country' => 'abc'
)
1 => array(
'name' => 'test2',
'country' => 'xyz'
)
2 => array(
'name' => 'test3',
'country' => 'pqr'
)
);
Any help is much appreciated. !
A dynamic version of Nigel's code would be to loop the array and merge each subarray.
$new = [];
foreach($arr as $subarr){
$new = array_merge($new, $subarr);
}
var_dump($new);
https://3v4l.org/np2ZD
You could simply merge the arrays...
$out = array_merge($arr[0], [$arr[1]]);
print_r($out);
Which gives...
Array
(
[0] => Array
(
[name] => test1
[country] => abc
)
[1] => Array
(
[name] => test2
[country] => xyz
)
[2] => Array
(
[name] => test3
[country] => pqr
)
)
I have 2 multidimensional arrays that I am working with:
$arr1 =
Array
([type] => characters
[version] => 5.6.7.8
[data] => Array
([Char1] => Array
([id] => 1
[name] =>Char1
[title] =>Example
[tags] => Array
([0] => DPS
[1] => Support))
[Char2] => Array
([id] => 2
[name] =>Char2
[title] =>Example
[tags] => Array
([0] => Tank
[1] => N/A)
)
)
etc...
$arr2=
Array
([games] => Array
([gameId] => 123
[gameType => Match
[char_id] => 1
[stats] => Array
([damage] => 55555
[kills] => 5)
)
([gameId] => 157
[gameType => Match
[char_id] => 2
[stats] => Array
([damage] => 12642
[kills] => 9)
)
etc...
Basically, I need almost all the data in $arr2... but only the Char name from $arr1. How could I merge or add the $arr1['name'] key=>value into $arr2 where $arr1['id'] is equal to $arr2['char_id'] as the "id" field of each array is the same number.
I've attempted using array_merge and array_replace, but I haven't come up with any working solutions. This is also all data that I am receiving from a 3rd party, so I have no control on initial array setup.
Thanks for any help or suggestions!
Actually, this is quite straighforward. (I don't think there a built-in function that does this.)
Loop $arr2 and under it loop also $arr1. While under loop, just add a condition that if both ID's match, add that particular name to $arr2. (And use some referencing & on $arr2)
Consider this example:
// your data
$arr1 = array(
'type' => 'characters',
'version' => '5.6.7.8',
'data' => array(
'Char1' => array(
'id' => 1,
'name' => 'Char1',
'title' => 'Example',
'tags' => array('DPS', 'Support'),
),
'Char2' => array(
'id' => 2,
'name' => 'Char2',
'title' => 'Example',
'tags' => array('Tank', 'N/A'),
),
),
);
$arr2 = array(
'games' => array(
array(
'gameId' => 123,
'gameType' => 'Match',
'char_id' => 1,
'stats' => array('damage' => 55555, 'kills' => 5),
),
array(
'gameId' => 157,
'gameType' => 'Match',
'char_id' => 2,
'stats' => array('damage' => 12642, 'kills' => 9),
),
),
);
foreach($arr2['games'] as &$value) {
$arr2_char_id = $value['char_id'];
// loop and check against the $arr1
foreach($arr1['data'] as $element) {
if($arr2_char_id == $element['id']) {
$value['name'] = $element['name'];
}
}
}
echo '<pre>';
print_r($arr2);
$arr2 should look now like this:
Array
(
[games] => Array
(
[0] => Array
(
[gameId] => 123
[gameType] => Match
[char_id] => 1
[stats] => Array
(
[damage] => 55555
[kills] => 5
)
[name] => Char1 // <-- name
)
[1] => Array
(
[gameId] => 157
[gameType] => Match
[char_id] => 2
[stats] => Array
(
[damage] => 12642
[kills] => 9
)
[name] => Char2 // <-- name
)
)
)
Iterate over $arr2 and add the data to it from the matching $arr1 array value:
$i = 0;
foreach($arr2['games'] as $arr2Game){
$id = $arr2Game['char_id'];
$arr2['games'][$i]['name'] = $arr1['data'][$id]['name'];
$i++;
}
Have not tested this code.
If I'm understanding you correctly, you want to add a name index to each of the arrays within the $arr2['games'] array.
foreach($arr2['games'] as $key => $innerArray)
{
$arr2['games'][$key]['name'] = $arr1['data']['Char'.$innerArray['char_id']]['name'];
}
I was wondering what is the best way to eliminate duplicates within an array? Currently I'm running through a foreach loop to actually get this array, is there a way to say, if id already exists, don't insert into array?
foreach($categories2Sugg as $Category2Sugg)
{
$category_stringArray2Sugg[] = array("id"=>$Category2Sugg->id,"name"=>$Category2Sugg->name,"pluralName"=>$Category2Sugg->pluralName,"shortName"=>$Category2Sugg->shortName);
}
Array
(
[0] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[1] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[2] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[3] => Array
(
[id] => 4bf58dd8d48988d14e941735
[name] => American Restaurant
[pluralName] => American Restaurants
[shortName] => American
)
)
Or maybe its easier to do another function if this array already exists, just delete some values to output a new array?
Thanks!
Try array_unique php function that will help.
Also Try
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
echo "<pre>";
print_r($unique);
echo "</pre>";
Above code is tested.
Complete Tested Code
<?php
$array = array
(
'0' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'1' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'2' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'3' => array
(
'id' => '4bf58dd8d48988d14e941735',
'name' => 'American Restaurant',
'pluralName' => 'American Restaurants',
'shortName' => 'American'
)
);
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
echo "<pre>";
print_r($unique);
?>
Cheers.
I have a multidimensional array like so:
$neighborhood => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
)
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
);
I would like to create another array (let's call it $array_of_moms) of all the moms in the neighborhood. Pulling them all in separately is doable, but not practical (like so):
$array_of_moms = array(
$neighborhood['the_smiths']['mom'],
$neighborhood['the_acostas']['mom'],
)
How do I create something like this:
$array_of_moms = $neighborhood['mom'];
$moms = array();
foreach($neighborhood as $family)
{
$moms[] = $family['mom'];
}
This'll iterate through each family in the array and add the mom to the new $moms array.
Using foreach, you can iterate through an array with variable indicies.
$array_of_moms = array();
foreach ($neighborhood AS $family) {
$array_of_moms[] = $family['mom']; // append mom of each family to array
}
If you can manipulate your array, you could:
<?php
$neighborhood = array(
'families' => array(
'the_smiths' => array(
'dad' => 'Donald',
'mom' => 'Mary',
'daughter' => 'Donna',
'son' => 'Samuel'
),
'the_acostas' => array(
'dad' => 'Diego',
'mom' => 'Marcela',
'daughter' => 'Dominga',
'son' => 'Sergio'
)
)
);
foreach ($neighborhood['families'] as $family => $folks) {
$neighborhood['moms'][] = $folks['mom'];
}
print_r($neighborhood);
?>
Which outputs:
Array
(
[families] => Array
(
[the_smiths] => Array
(
[dad] => Donald
[mom] => Mary
[daughter] => Donna
[son] => Samuel
)
[the_acostas] => Array
(
[dad] => Diego
[mom] => Marcela
[daughter] => Dominga
[son] => Sergio
)
)
[moms] => Array
(
[0] => Mary
[1] => Marcela
)
)
http://codepad.org/xbnj5UmV