PHP array in alphabetic order in option drop down - php

the text below takes google sheet json output, turns it into php array and then filters just by football club. the outcome is a drop down list of football clubs, sorted in random order. i am having trouble sorting them by alphabetical order.
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
//create array to store
$clubs=array();
//loop for each into array
foreach ($data['feed']['entry'] as $item)
{
$clubs[]= $item['gsx$clubs']['$t'];
}
//take array and get unique clubs
$clubs =array_unique($clubs);
//start select html
echo '<select>';
//print out unique clubs in option dropdown
foreach ($clubs as $key => $club) {
echo '<option>' . $club . '</option>' ;
}
//finish select html
echo '</select>';
when i print out print_r($clubs); it comes out like this
Array ( [0] => AFC Bournemouth [1] => Chelsea [2] => Wolverhampton Wanderers [3] => Crystal Palace [4] => Burnley [5] => Brighton & Hove Albion [6] => Tottenham Hotspur [8] => West Ham United [11] => Everton [12] => Manchester City [14] => Aston Villa [16] => Arsenal [20] => Manchester United [21] => Watford [23] => Sheffield United [28] => Southampton [30] => Newcastle United [39] => Norwich City [51] => Liverpool [71] => Leicester City )
so far i have already tried sort($clubs) and it doesnt seem to work

php code:
$asd = array(
"AFC Bournemouth",
"Chelsea",
"Wolverhampton Wanderers",
"Crystal Palace",
"Burnley",
"Brighton & Hove Albion",
"Tottenham Hotspur"
// ...
);
echo "<pre>";
print_r($asd);
echo "</pre>";
sort($asd);
echo "<pre>";
print_r($asd);
echo "</pre>";
output:
Array
(
[0] => AFC Bournemouth
[1] => Chelsea
[2] => Wolverhampton Wanderers
[3] => Crystal Palace
[4] => Burnley
[5] => Brighton & Hove Albion
[6] => Tottenham Hotspur
)
Array
(
[0] => AFC Bournemouth
[1] => Brighton & Hove Albion
[2] => Burnley
[3] => Chelsea
[4] => Crystal Palace
[5] => Tottenham Hotspur
[6] => Wolverhampton Wanderers
)
no problem, sorted alphabetically.
write what you want to receive in array?

There are some sorting functions for PHP arrays already. I think sort() is what you want. Have to tried it? https://www.w3schools.com/php/php_arrays_sort.asp
Usage:
<?php
$array = ["Newcastle United", "AFC Bournemouth", "Wolverhampton Wanderers", "Chelsea"];
sort($array);
print_r($array);
?>
Output
Array (
[0] => AFC Bournemouth
[1] => Chelsea
[2] => Newcastle United
[3] => Wolverhampton Wanderers
)

Related

How can i insert this array into the database

How i will make a this array value converted into a string for enable me to insert it to the database.
$myArray = Array
(
[0] => Array
(
[code] => 1
[name] => Array
(
[content] => Ohtels Villa Dorada
)
[description] => Array
(
[content] => This hotel is located about 150 metres from the fine sandy beach. The lively centre of Cambrils is approximately 10 km away and can be easily reached by the public bus services. There is a stop for public transport right in front of the hotel. The immediate vicinity offers a diverse range of shopping and entertainment facilities including boutiques, restaurants and bars. This hotel comprises a total of 260 rooms spread over 5 floors. Dining options include a café, a bar and an air-conditioned buffet restaurant with highchairs for infants. The tastefully decorated, cosy rooms come with a balcony and satellite TV.
)
[countryCode] => ES
[stateCode] => 43
[destinationCode] => SAL
[zoneCode] => 10
[coordinates] => Array
(
[longitude] => 1.152529
[latitude] => 41.068407
)
[categoryCode] => 3EST
[categoryGroupCode] => GRUPO3
[chainCode] => OHTEL
[accommodationTypeCode] => HOTEL
[boardCodes] => Array
(
[0] => BB
[1] => AI
[2] => HB
[3] => FB
[4] => RO
)
[segmentCodes] => Array
(
[0] => 37
)
[address] => Array
(
[content] => Carrer Del Vendrell,11
)
[postalCode] => 43840
[city] => Array
(
[content] => SALOU
)
[email] => comercial#ohtels.es
[license] => HT-000473
[web] => http://www.ohtels.es/
[lastUpdate] => 2019-03-14
[S2C] => 4*
[ranking] => 96
)
[1] => Array
(
[code] => 1
[name] => Array
(
[content] => Sample
)
[description] => Array
(
[content] => This hotel is located about 150 metres from the fine sandy beach. The lively centre of Cambrils is approximately 10 km away and can be easily reached by the public bus services. There is a stop for public transport right in front of the hotel. The immediate vicinity offers a diverse range of shopping and entertainment facilities including boutiques, restaurants and bars. This hotel comprises a total of 260 rooms spread over 5 floors. Dining options include a café, a bar and an air-conditioned buffet restaurant with highchairs for infants. The tastefully decorated, cosy rooms come with a balcony and satellite TV.
)
[countryCode] => ES
[stateCode] => 43
[destinationCode] => SAL
[zoneCode] => 10
[coordinates] => Array
(
[longitude] => 1.152529
[latitude] => 41.068407
)
[categoryCode] => 3EST
[categoryGroupCode] => GRUPO3
[chainCode] => OHTEL
[accommodationTypeCode] => HOTEL
[boardCodes] => Array
(
[0] => BB
[1] => AI
[2] => HB
[3] => FB
[4] => RO
)
[segmentCodes] => Array
(
[0] => 37
)
[address] => Array
(
[content] => Carrer Del Vendrell,11
)
[postalCode] => 43840
[city] => Array
(
[content] => SALOU
)
[email] => comercial#ohtels.es
[license] => HT-000473
[web] => http://www.ohtels.es/
[lastUpdate] => 2019-03-14
[S2C] => 4*
[ranking] => 96
)
)
i want all of the value of the $myArray would be inserted to the database
But also i used foreach loop to store it to a $variable and i will just concatinate the value into the query.
INSERT INTO test(code,contents) VALUES $variable;
Here is what am i doing.
$hotel_content = '';
foreach($myArray as $content)
{
$hotel_content .= "(".$content['code'].",".json_encode($content)."),";
}
$hotel = "INSERT INTO test(code,contents) VALUES ".rtrim($hotel_content,",").';';
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $hotel) )
{
echo "You have successfully inserted the data.";
}
else
{
echo "Error: " . $hotel . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
Way 1:
You can insert full array by converting it to sting. So you can use PHP serialize function before insert.
$serialized_data = serialize($myarray);
then user $serialized_data into your insert query.
Ref: https://www.php.net/manual/en/function.serialize.php
Note you've to unserialize it when you'll use this data. So after retrieving from database unserialize it by unserialize() function.
Another way: you can use json_encode() function to store array. and you'll also need to use json_decode() when/where you'll use this data.
Ref: https://www.php.net/manual/en/function.json-encode.php
Define table column as longText
like this
$table->longText('column_name');
Then save data into it as JSON STRING
$value = json_encode($myArray);

partial search in multidimensional array

Hi i have an array like below. I want to search partial data from this array.
for example: i want to search "New Delhi" then i got array where city = Delhi, and search "Raigad" then got array where city = Raigarh
Array(
[56] => Array
(
[city] => Davangere
[product_id] => 14
[tier] => Tier 4
)
[57] => Array
(
[city] => Dehradun
[product_id] => 14
[tier] => Tier 3
)
[58] => Array
(
[city] => Delhi
[product_id] => 14
[tier] => Metro
)
[59] => Array
(
[city] => Delhi
[product_id] => 14
[tier] => Metro
)
[60] => Array
(
[city] => Raigarh
[product_id] => 14
[tier] => Metro
)
)
Make use of similar_text to attain this -
$finalArray = array();
$searchString = "New Delhi";
//Loop through your array
foreach ($your_array as $key => $value) {
similar_text($searchString, $value['city'], $percentageSimilarity);
//if percentage similarity between the text is above 70%, add to to our final array
if ($percentageSimilarity > 70) {
$finalArray[$key] = $value;
}
}
var_dump($finalArray);
Works for Delhi and Raigarh.

Remove Duplicate Arrays in PHP for laravel framework

I have more than 4 arrays in single variable as shown below
$myArray = Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas ) Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas )
Now i need to compare each and every array of [2] index.
If second index ([2] => USA) is present in some other array then delete duplicate array.
Finally the arrays should look like this
Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas ).
I have tried this but not able to sort it out.
$myArray = array_map("unserialize", array_unique(array_map("serialize", $myArray)));
Is there any way?
You can use a foreach loop for this, like DEMO:
$match = [];
foreach($myArray as $key => $value)
{
if(!in_array($value[2], $match))
{
$match[] = $value[2];
continue;
}
unset($myArray[$key]);
}
This will remove all of the arrays which have duplicate value for [2]
You need to iterate through your array with two loops and check the second index value in each of the inner arrays and if there is a duplicated value you can just unset the second one.
Here is a piece of code that should do well:
<?php
for($i=0; $i < count($myArray); $i++) {
for($j=$i+1; $j < count($myArray); $j++) {
if ($myArray[$i][2] == $myArray[$j][2]) {
unset($myArray[$j][2]);
}
}
}
P.S: The code is not tested and may need some modifications, but you could get the main idea.

How do I print out this multidimensional php array into a json object?

I have a multidimensional php array which I am trying to printout in json format
This is the array
Array ( [0] => Array ( [name] => Zeninjor Enwemeka [title] => At Boston Forum, Federal And Local Officials Discuss Region�s Transportation Future [published] => 2015-10-14 12:22:00 ) [1] => Array ( [name] => Zeninjor Enwemeka [title] => Boston�s Transportation Future? City Releases Report Detailing Public�s Transit Goals [published] => 2015-10-09 09:17:00 ) [2] => Array ( [name] => Ryan caron King [title] => Sen. Murphy Seeks Feedback From �Fed Up� Car Commuters [published] => 2015-10-15 16:25:00 ) [3] => Array ( [name] => patrick skahill [title] => Solar Installations Skyrocket, But Connecticut Consumers Still Need to Do Their Homework [published] => 2015-10-15 09:12:00 ) )
I have tried this but it did not work:
print_r($output_result);
$output = array();
foreach($output_result as $v) {
$output[key($v)] = current($v);
}
echo json_encode($output);

extract array from multidimensional array

i have an array which is like this
Array
(
[0] => Array
(
[name] => Amanda Coleman
[id] => 98764676778
)
[1] => Array
(
[name] => Hashimi Sultana
[id] => 876304848
)
[2] => Array
(
[name] => Maren Shawesh
[id] => 988363747
)
[3] => Array
(
[name] => Ajo Khan
[id] => 039494857587
)
[4] => Array
(
[name] => Negar Jan
[id] => 948437484748
)
[5] => Array
(
[name] => Mehran Khan
[id] => 3948474947
)
[6] => Array
(
[name] => Sal Man
[id] => 039383734647
)
this is upto 566 mean this is my facebook friends name and ids
what i am trying to do is i want to make autocomlete of facebook friends
which work fine for me its showing what i want to do but i need the ids also against name
here is my code
if(isset($_REQUEST['queryString'])) {
lets $var = fa
$var = ucfirst ($_REQUEST['queryString']); //making first character uppercase for matching with fb name
$friends_inner=$_SESSION['friends'];
echo "<pre>";
print_r($friends_inner);
echo "</pre>";
the output is above array
for($i=0; $i<sizeof($friends_inner); $i++)
{
$selected_friend=$friends_inner[$i];
$selected_friend_id=$selected_friend['id']; //array of ids
$selected_friend_name=$selected_friend['name']; // array of names
$name[$i]=$selected_friend_name;
}
$result=preg_grep('/^'.$var.'.*/', $name);//returns array matching with requested alphabet from textbox which work fine dispalaying names
echo "<pre>";
print_r($result);
echo "</pre>";
here is the output
Array
(
[17] => Fazal Muhammad
[18] => Fawad Ahmad
[39] => Fayaz Zafar
[42] => Farhan Bogra
[66] => Farzana KArim Elora
[81] => Fahim Khan
[92] => Fahad Shams
[119] => Fazal Yazdan
[166] => Fakhar Alam
[173] => Faheem Ur Rahman
[183] => Fawaid Khan
[187] => Faizan Sabir
[258] => Fayaz Ali
[269] => Faizan Khattak
[308] => Faridullah Khan
[411] => Fawad Qamar
[446] => Fahad Khan
[458] => Fahad Khan
[507] => Faisl Qureshi
[529] => Faisal Khan
[538] => Faiza Baloch
[555] => Fawad Khan
)
as it its index is not sequentially so i am diong so to make it start from zero
$final_result=array();
$maxindex = max(array_keys($result));
for($i=0;$i<=$maxindex;$i++){ //returns array that start with zero
if(isset($result[$i])){
array_push($final_result,$result[$i]);
}
}
echo "<pre>";
print_r($final_result);
echo "</pre>";
the result is
Array
(
[0] => Fazal Muhammad
[1] => Fawad Ahmad
[2] => Fayaz Zafar
[3] => Farhan Bogra
[4] => Farzana KArim Elora
[5] => Fahim Khan
[6] => Fahad Shams
[7] => Fazal Yazdan
[8] => Fakhar Alam
[9] => Faheem Ur Rahman
[10] => Fawaid Khan
[11] => Faizan Sabir
[12] => Fayaz Ali
[13] => Faizan Khattak
[14] => Faridullah Khan
[15] => Fawad Qamar
[16] => Fahad Khan
[17] => Fahad Khan
[18] => Faisl Qureshi
[19] => Faisal Khan
[20] => Faiza Baloch
[21] => Fawad Khan
)
$ids_of_result=array();
now here is the big problem i want to extract all user ids from $friends_inner array which name equal to my $final_result array.i am doing so but the problem is that it goes upto last index i-e 22 and than through error that index 22 and ahead is not valid offset.how can i extract the ids from this $friends_inner which is my main array
for($j=0; $j<sizeof($friends_inner); $j++){
$selected_friend=$friends_inner[$j];
if($final_result[$j] == $selected_friend['name']){
echo $selected_friend['name'];
echo $selected_friend['id'];
array_push($ids_of_result,$selected_friend['id']);
//returns array of ids against result
}
}
echo "<pre>";
print_r($ids_of_result);
echo "</pre>";
it result in
Array
(
)
$counter=0;
foreach($final_result as $key=>$value){
echo '<li onClick="fill(\''.$ids_of_result[$counter].'\');">'.$value.'</li>';
$counter++;
}
}
please help me my code work fine in sense of autocomplete but i want the ids too.Graph api does not provide the id from name.if so i would not write much code.any help me thanx in advance
?>
function sort_arrays($final_result,$friends_inner) {
$ids_of_result = array();
foreach($final_result as $fnl_rslt){
foreach($friends_inner as $frnd_in){
if($fnl_rslt == $frnd_in['name']){
//echo 'Name : '.$frnd_in['name'].'<br>';
//echo 'Id : '.$frnd_in['id'].'<br>';
array_push($ids_of_result,$frnd_in['id']);
}
}
}
return $ids_of_result;
}
$ids_of_result = sort_arrays($final_result,$friends_inner);

Categories