This question already has answers here:
GROUP_CONCAT comma separator - MySQL
(3 answers)
Closed 2 years ago.
I have an array with film information and the times when they will be shown in the cinema. each showing is another result, so one film can be in the array multiple times. I want to combine duplicate film entries into one and put all shows in another dimension in the new array. The formatting is this:
Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => datetime )
Should be formatted into:
Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => Array
( [0] => datetime0
[1] => datetime1
... )
)
Has anyone an idea how to combine it after "title" and put all entries for datetime in a new dimension.
Thank for your help!
Suppose that title is unique (no two movies with the same title). Then this would work:
$newArray = [];
foreach ($array as $element) {
if (array_key_exists($element['title'], $newArray)) {
$newArray[$element['title']]['datetime'][] = $element['datetime'];
} else {
$element['datetime'] = [$element['datetime']];
$newArray[$element['title']] = $element;
}
}
$newArray = array_values($newArray);
However, as other comments pointed out, this is not an optimal solution, and you may want to think about the database structure or use something like CONCAT in SQL to return list of dates separated by a symbol, then use explode in PHP.
Related
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have an array that contains player data. This array changes according to the number of players. The array looks like this:
Array
(
[0] => Array
(
[Id] => 0
[Name] => Playername1
[Frags] => -3
[Time] => 339
[TimeF] => 05:39
)
[1] => Array
(
[Id] => 0
[Name] => Playername2
[Frags] => 0
[Time] => 7
[TimeF] => 00:07
)
)
I want to get from this array from each player only the player name [name]. How do I do this? The output should be a string that looks something like this: Playername1, Playername2
I have not found anything on the Internet or on YouTube. The answer is certainly simple and obvious, but I have not found it.
Im using PHP 8.0.13.
$names = implode(',', array_column($arr, 'name'));
echo $names;
array_column: return the values from a single column in the input array.
implode: Join array elements with a string.
try something like this:
$player_names = '';
foreach($your_array as $key => $value){
$player_names .= $value['Name'].', ';
// this should concatenate all the player names
}
This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 2 years ago.
I would like to collate data from multiple different data sources into one numeric array using foreach loops, however I am having some trouble building my array in the expected format. I would like to keep the key numeric.
For example, if I had two data sources: $fruit_data and $flavor_data and my code was:
foreach($fruit_data as $fruit){
$fruits[]['name'] = $fruit['name'];
}
foreach($flavor_data as $flavor){
$fruits[]['flavor'] = $flavor['taste'];
}
The data is added to the array with separate numeric keys, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
)
[1] => Array
(
[flavor] => Example Flavor 1
)
[2] => Array
(
[name] => Example Name 2
)
[3] => Array
(
[flavor] => Example Flavor 2
)
)
However, my desired output is to display the data under the same numeric key, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
[flavor] => Example Flavor 1
)
[1] => Array
(
[name] => Example Name 2
[flavor] => Example Flavor 2
)
)
Could somebody please explain where I am going wrong, and if possible, link me to a resource that explains how to overcome this issue? It may be that I have a fundamental misunderstanding of multidimensional arrays, but I cannot seem to find any references to this issue.
Any help is much appreciated.
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit['name'],
'flavor' => $flavor_data[$index]['taste']
];
}
Same as
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit_data[$index]['taste'],
'flavor' => $flavor_data[$index]['taste']
];
}
This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed 3 years ago.
Here is the array which I have,
Array
(
[0] => Array
(
[number] => 2
[name] => ABC
)
[1] => Array
(
[number] => 3
[name] => ABC
)
[2] => Array
(
[number] => 1
[name] => XYZ
)
[3] => Array
(
[number] => 2
[name] => XYZ
)
)
what I want is...
Array
(
[0] => Array
(
[name] => XYZ
[number] => 1,2
)
[1] => Array
(
[name] => ABC
[number] => 2,3
)
)
it should be unique by name.
And numbers of particular name will be in comma separated.
please help me guys
Thanks in advance
You can do this in one loop but I prefer to do it in two loops as it will be easier to get the correct output with implode than adding commas and then removing them again.
Loop the array and build an associative array and make an array to collect the numbers.
Then loop again and implode the numbers to a string.
foreach($arr as $sub){
$res[$sub['name']]['name'] = $sub['name'];
$res[$sub['name']]['number'][] = $sub['number'];
}
foreach($res as &$sub){
$sub['number'] = implode(",", $sub['number']);
}
$res = array_values($res);
var_dump($res);
https://3v4l.org/PbGsu
You can use array_map, array_key_exists, array_values to get the desired results
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['name'], $res) ?
($res[$v['name']]['number'] = $res[$v['name']]['number'].','.$v['number'])
:
($res[$v['name']] = ['number' => $v['number'],'name' => $v['name']])
;
}, $arr);
$res = array_values($res);
Live Demo
To use
array_merge()
function.
If suppose your key values are same, your key and values are overwrites after merge your array.
This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 7 months ago.
I have an array of array that looks like this:
Array
(
[0] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[1] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[2] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
I want to set the key of the parent array with the value of id, so the result array looks like this:
Array
(
[I100] => Array
(
[id] => I100
[name] => Mary
[gender] => F
)
[I101] => Array
(
[id] => I101
[name] => John
[gender] => M
)
[I245] => Array
(
[id] => I245
[name] => Sarah
[gender] => F
)
)
If possible I'd like to avoid using an additional loop to go through the array and creating a new array to store each item with the proper key, as the array can have thousands of items.
Thanks in advanced!
Despite your caveat, a loop is the obvious solution:
$newArray = [];
foreach($oldArray as $item)
$newArray[$item['id']] = $item;
If the problem you have is not specifically with a loop, but rather creating a copy of the array is causes excessive memory consumption, then you can edit the array in place, with a for loop:
for($i=0; $i<count($oldArray); $i++){
$oldArray[$oldArray[$i]['id']] = $oldArray[$i];
unset($oldArray[$i]);
}
Note this works because the id elements are alphanumeric strings, if they where simple integars then the above code could overwrite sections.
The only other solution is to build the correct array in the 1st place, in a similar manner.
For example, using PDO::fetch instead of PDO::fetchAll:
//$newArray = $sth->fetchAll(PDO::FETCH_ASSOC);
$newArray = [];
while($row = $sth->fetch(PDO::FETCH_ASSOC))
$newArray[$row['id']] = $row;
You can't overwrite keys while iterating through an array "on the fly". So here is solution with array_map which produces an array with needed structure:
// assuming $arr is your initial array
$result = [];
array_map(function($a) use (&$result){
$result[$a['id']] = $a;
}, $arr);
// $result contains the needed array
You can add needed key during creation of this array.
I have an array that is put together. It's basically 24 data points across 7 stations. Each station has a data point each hour and a new sub0array is created for each data point. The problem with this, is I now want to split the data up based on station so I can sort it. When I go to do that array_filter doesn't work for me. I wanted to basically combine all of the values that have the same row 0 result in each sub-array. but keep each data point based on them. Row 0 is the station name. Here is an example of what the array looks like. There are 160 sub arrays. All I need to do is combine them together based on Station name. I was going to do this based on Array value, but the problem is if a data-point is missing, it breaks that logic.
Array
(
[0] => Array
(
[0] => STATIONONE
[1] => 02/22/15 04:00:00 PM
[2] => SW
[3] => Array
(
[0] => 4.51
)
[4] => MPH
[5] => Array
(
[0] => 16.1
)
[6] => MPH
)
[1] => Array
(
[0] => STATIONONE
[1] => 02/22/15 05:00:00 PM
[2] => S
[3] => Array
(
[0] => 2.7
)
[4] => MPH
[5] => Array
(
[0] => 9.61
)
[6] => MPH
)
And it just keeps repeating till I have 23 Values. Then the next station.
So 0-22 subarray value = station 1
23-45 subarray value = station 2
etc.. just stating to help show what I am trying to do.
It isn't entirely clear what you expect your output to be, but this might get you there:
$entriesByStation = []
foreach ($entries as $entry) {
$entriesByStation[$entry[0]] = $entry;
}
This will group all the the entries by station name in the $entriesByStation array
The accepted answer got me close into figuring this out. I had to do this by station though. So I just created 7 foreach statements and created an array for each station. This way I can also merge the array together if needed.
# Parse our All Data and set station
foreach ($array as $entry) {
if ($entry[0] === "STATIONONE"){
$S1pkwsite = ($entry[0]);
$S1pkwvalue = ($entry[5][0]);
$S1pkwdate = ($entry[1]);
$S1pkwunit = ($entry[6]);
$S1wspvalue = ($entry[3][0]);
$S1wspunit = ($entry[4]);
$S1wdrvalue = ($entry[2]);
$S1pkwdataarray[] = array('SiteName'=>$S1pkwsite,'DATE'=>$S1pkwdate,'WDR'=>$S1wdrvalue,'VALUE'=>$S1pkwvalue,'UNIT'=>$S1pkwunit);
}
}
array_push ($Stationone_data, $pkwdataarray);
$Stationone_data = array_shift($Stationone_data);