php array sorting and grouping - php

I have an array of Towns that have no sorting whatsoever. I would like to sort by the [category][3] which is the province and then the [category][0] which is the region and display each Grouped Province with its regions and then towns underneath it. So the following array:
Array
(
[0] => Array
(
[name] => Name One
[id] => 1
[link] => http://mylink1.com
[category] => Array
(
[0] => Region 1
[1] => Town 7
[2] => Country
[3] => Province 2
)
)
[1] => Array
(
[name] => Name Two
[id] => 2
[link] => http://mylink2.com
[category] => Array
(
[0] => Region 1
[1] => Town
[2] => Country
[3] => Province 3
)
)
[2] => Array
(
[[name] => Name Three
[id] => 3
[link] => http://mylink3.com
[category] => Array
(
[0] => Region 1
[1] => Town 5
[2] => Country
[3] => Province 2
)
)
[6] => Array
(
[name] => Name Four
[id] => 4
[link] => http://mylink4.com
[category] => Array
(
[0] => Region 1
[1] => Town 1
[2] => Country
[3] => Province 1
)
)
)
... should end up looking like this:
Country (all the same)
Province 1
- Region 1
- - Town 1 name, id, link
Province 2
- Region 1
- - Town 5 name, id, link
- - Town 7 name, id, link
Province 3
- Region 1
- - Town 1 name, id, link
Province is the Primary Grouping factor, then sorted by Region, the Towns in no particular order but I guess Alphabetically would make sense.
I have managed to sort the array by Category using this reference: Sort Multi-dimensional Array by Value but cannot fathom how to sort any further without referencing the Province specifically in a loop by using its name. i.e.
/// shortened version..
foreach($array as $key=>$value)...
if($value == "Province 1") : do something here with these matches
... etc
Any help would be appreciated.

Take a look at the uasort() function:
http://www.php.net/manual/en/function.uasort.php

I don't think that you can do this in one step.
You can group your values like this:
$grouped = array();
foreach ($data as $group)
{
$grouped[ $group['category'][3] ][ $group['category'][0] ][ $group['category'][1] ] = array(/* ... */);
}
But you will still have to sort every array (and it's sub-arrays) using ksort().
You should check, whether you can get the values already presorted. If you, for example, are using a database to retrieve this values, it would be quite trivial to sort them in the database and bring them in the correct (grouped) structure in your PHP code.

looping through the array I've used a switch for the category I'm looking for and then built another array for each group. from there I can sort by region:
foreach($arr as $town){
switch($town['blogcats']){
case "Province 1" : $province1[] = $town;
break;
case...
etc
}
}
Then each new grouped array can be output:
foreach($province1 as $eachtown) {
echo $newtown['name'];
... and so forth.
}
Within the second loop sorting could be done on the Region.
Each Province is manually referenced in a list on my page which also gives me control over placement.
Howver, this answer could also be improved... but the above works without too much effort.

Related

Counting entries in sub/subarray

I am working on a chat.
I have an array that contains the info regarding the room
(in the example below, 2 rooms (the lounge, the beach)).
I have an issue when I have an empty room (in the example the beach), as it contains by default no user, (which is a Null user).
$roomNusers=Array (
[The Lounge] =>
Array ( [id] => 1
[privacy] => public
[users] => Array
[QUICHE POIREAU] => Array
[smiley] => smi_smile.gif
[name] => QUICHE POIREAU
[state] => NULL
[id] => 1 )
[JOHN DOE] => Array
[smiley] => smi_smile.gif
[name] => Joe FRANC
[state] =>
[id] => 40 )
[The Beach] => Array
[id] => 2
[privacy] => public
[users] => Array
[Null] => Array
[smiley] => Null
[name] => Null
[state] => Null
[id] => Null
I am trying to count, in my array, the number of users currently present in the room.
Looking around Stack Overflow, I managed to find the solution I wanted:
foreach($roomNusers as $room => $value)
{
echo $room.' user count:'.count($room['users'])
}
This output:
The lounge user count: 2
The beach user count: 1
My issue is that it counts the user [null] in the beach.
How can I count the number of users not null per room?
I thought of a workaround with something similar to:
$countperroom= .count($room['users'])-1;
if(isset(end([$room]['users']))){$countuser+1;}
In this, the last user is empty, I do not add an user, but I do not know how to write this.
Rather than counting the number of values in $room['users'], you could count the number of keys after filtering them to remove empty keys:
foreach ($rooms as $name => $room) {
$users = count(array_filter(array_keys($room['users'])));
echo "$name: $users users\n";
}
Output (for your sample data):
The Lounge: 2 users
The Beach: 0 users
Demo on 3v4l.org

php separate multilingual array and show in loop [duplicate]

This question already has an answer here:
How to echo the key:value pairs of a sub array? PHP
(1 answer)
Closed 2 years ago.
I add array to mysql database for multilingual(2 and 1 is language id in array) data like this:
{
"2":[
{"title":"french title one","address":"french title one"},
{"title":"french title two","address":"french title two"},
{"title":"french title three","address":"french title three"}
],
"1":[
{"title":"english title one","address":"english title one"},
{"title":"english title two","address":"english title two"},
{"title":"english title three","address":"english title three"}
]
}
in print_r i see this:
Array
(
[2] => Array
(
[0] => Array
(
[title] => french title one
[address] => french address one
)
[1] => Array
(
[title] => french title two
[address] => french address two
)
[2] => Array
(
[title] => french title three
[address] => french address three
)
)
[1] => Array
(
[0] => Array
(
[title] => english title one
[address] => english address one
)
[1] => Array
(
[title] => english title two
[address] => english address two
)
[2] => Array
(
[title] => english title three
[address] => english address three
)
)
)
Now I have language id like this:
$language_id = 1;
I need to show loop(foreach) of data array only for language id 1 like this:
english address one
english address two
english address three
how do can i separate multilingual array?!
Very easy - $array it is your php array
foreach($array[1] as $val){ echo"<a href='$val[title]'>$val[address]</a>";}
/* more flexible */
$language_id = 1;
$href = 'title';
$txt = 'address';
foreach($array[$language_id] as $val){ echo"<a href='$val[$href]'>$val[$txt]</a>";}
If you need only a part - loop this part only.

PHP conditions within an array

Is it possible to use conditions within an array:
Uses define('COMPANY_ADDRESS_1','something here'); << if empty don't want to be in the array
$invoice->setFrom(array(COMPANY_NAME,COMPANY_ADDRESS_1,COMPANY_ADDRESS_2,COMPANY_TOWN,COMPANY_COUNTY,COMPANY_POSTCODE));
For example COMPANY_ADDRESS_2 is not set and doesn't show in the array so at the moment the output ends up like:
company name
company address 1
<<<<<<<<<< leaves a gap here
company town
company county
company postcode
The output is fine but if nothing is set for example COMPANY_ADDRESS_2 I want to remove it from the array altogether as it's passed to a PDF generator and currently writing as a blank line.
According to your question i think your array look like below:-
Array
(
[0] => company name
[1] => company address 1
[2] =>
[3] => company town
[4] => company county
[5] => company postcode
)
So you need to do in following manner:-
<?php
$result = array('company name','company address 1','','company town','company county','company postcode');//original array
$newArray = array();
foreach($result as $value){
if($value != ''){
$newArray[] = $value;
}
}
echo "<pre/>";print_r($newArray);
echo "<pre/>";print_r(array_filter($result));
?>
Output:-
Array //null value or empty value removed and array is re-indexed
(
[0] => company name
[1] => company address 1
[2] => company town
[3] => company county
[4] => company postcode
)
Array //null value or empty value removed without re-indexed
(
[0] => company name
[1] => company address 1
[3] => company town
[4] => company county
[5] => company postcode
)

create sub Array on join instead of new entries

I have 4 lectures where each lecture has it's own name:
jbc2014_lezingen
Then for each lecture there will be questions, in this case 2 for each lecture:
jbc2014_vragen
I use this query:
$query = "SELECT * FROM jbc2014_lezingen
INNER JOIN jbc2014_vragen
ON jbc2014_lezingen.id=jbc2014_vragen.lezing_id";
This results in something like:
[0] => Array
(
[id] => 1
[lezing_naam] => lezing 1
[lezing_id] => 1
[vraag] => foobar?
)
[1] => Array
(
[id] => 2
[lezing_naam] => lezing 1
[lezing_id] => 1
[vraag] => foobar?
)
etc.
So the array size is based on the amount of the questions, not the amount of the lectures.
I would like something like:
[0] => Array
(
[id] => 1
[lezing_naam] => lezing 1
[lezing_id] => 1
[questions] Array (
[0] => [vraag] => foobar?
[1] => [vraag] => foobar?
)
)
Where the questions are in an array (vraag means question).
How can this be done?
Later on I need the multiple choice answers in an array inside the questions as well. But I think that won't be hard after having this one fixed.
The closest thing you could do is something like this -
SELECT jbc2014_lezingen.id as lezing_id,
GROUP_CONCAT(vraag) as vraags
FROM jbc2014_lezingen
INNER JOIN jbc2014_vragen
ON jbc2014_lezingen.id=jbc2014_vragen.lezing_i
GROUP BY jbc2014_lezingen.id
and then just get the values with
explode(",",$row['vraags']);
or create another array with something like this
foreach($raw_result as $key => $value){
$new_array[$key]['lezing_id'] = $value['lezing_id'];
$new_array[$key]['vraags'] = explode(",",$value['vraags']);
}

PHP foreach loop to build multi array

I'm trying to build a multi array with this structure:
Array
(
[2] => Array //this is the user's unique ID
(
[name] => Jack
[location] => Somerville, Massachusetts, United States
[cars] => Array
(
[10] => Toyota //this is the car's unique ID
[11] => Porsche
)
)
[5] => Array
(
[name] => Luke
[location] => Schwelm, North Rhine-Westphalia, Germany
[cars] => Array
(
[1] => Honda
[2] => VW
[5] => Maserati
)
)
[1] => Array
(
[name] => Jabba
[location] => Denver, Colorado, United States
[cars] => Array
(
[3] => Tesla
)
)
)
I am using this foreach loop but am stuck in getting the cars array embedded within the search data array.
Each user may have more than one car so I would need to loop through all cars for each user, generate that array, and put it in the original foreach loop.
$search_data = array();
foreach ($query->result() as $row) {
$search_data[$row->id] = array(
'name' => $row->name,
'location' => $row->location,
'cars' => array($row->car_id), //this is where I need to insert another array
);
}
return $search_data;
Any suggestions how to do this?
Thanks for helping!
SAMPLE TABLE DATA
USER NAME LOCATION CARS
2 JACK A TOYOTA
2 JACK A PORSCHE
5 LUKE B HONDA
5 LUKE B VW
5 LUKE B MASERATI
1 JABBA C TESLA
It seems that you are creating the array through a database table. So can you please give 2 or more sample data. it'll be easier to give an answer if sample data is there.
Edit:
Well this might not be the best code but I think you'll be able to figure out a better way after seeing this
$id = $row['id'];
if (!isset($search_data[$id])){
$search_data[$id] = array();
}
$search_data[$id]['name'] = $row['name'];
$search_data[$id]['location'] = $row['location'];
if (isset($search_data[$id]['cars'])) {
array_push($search_data[$id]['cars'],$row['cars']);
}else{
$search_data[$id]['cars'] = array($row['cars']); //this is where I need to insert another array
}

Categories