New array from multidimensional array - url parsing - php

I have the following URL: myexample.com/?city=Miami
and a large array (23k)
$e = $_GET["city"];
$myArray = array
(
array ("Miami","Florida"),
array ("Key West","Florida"),
array ("NOLA", "Luisiana"),
array ("Baton Rouge","Luisiana")
);
I'm looking for a solution to dynamically create a new array of cities that matches the state of the city in the URL, and echo all the cities from that state.
In other words:
if myexample.com/?city=NOLA, I would like to echo "Baton Rouge" and "NOLA" (from Luisiana)
if myexample.com/?city=Miami, echo "Key West" and "Miami" (from Florida)
etc.
There are quite a few similar questions answered already (here, here, but looping is not one of strengths (beginner).
Thank you.
EDIT1:
$resArray = array();
foreach($myArray as $arr) {
if(in_array($e, $arr))
$resArray[] = $arr;
}
print_r($resArray);
Result: Array ( [0] => Array ( [0] => Miami [1] => Florida ) )

First of all I would restructure your myArray in something like the following:
$stateAndCities = [
"Florida" => ["Miami","Key West"],
"Luisiana" => ["NOLA", "Baton Rouge"]
];
after that you can better handle the input and give an easier output
$city = $_GET["city"];
$resultCities = [];
$resultState = "";
// Loop over all states with their cities
foreach($stateAndCities as $state => $cities) {
if(in_array($city, $cities)){ // if the given $city is in the $cities?
$resultCities = $cities;
$resultState = $state;
break;
}
}
if(!empty($resultState) && !empty($resultCities)){ // ensure that the city was found in any state
echo $resultState;
print_r($resultCities);
}
(the code is not tested!)
Manual:
http://php.net/in_array
http://php.net/empty

Related

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

Iterate over JSON file using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a JSON file containing a list of universities around the world. I want to get only specific universities where a field in the array matches what I need to select. The problem I face is that each university has it's own ID number which makes me unable to figure out how to iterate over the Array. The JSON file can be found on this GitHub repo.
The code that makes me convert the JSON file to an array:
<?php
$json = file_get_contents('universities_list.json');
$universityArray = json_decode($json, true);
print_r($universityArray);
?>
And a sample of what I get is:
[2942] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => aast.edu
[name] => Arab Academy for Science & Technology
[web_page] => http://www.aast.edu/
)
[2943] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => akhbaracademy.edu.eg
[name] => Akhbar El Yom Academy
[web_page] => http://www.akhbaracademy.edu.eg/
)
What is the best or appropriate way to print out only the universities with alpha_two_code == 'EG' or == 'Egypt' for example?
I read the documentation on foreach loop and the examples as well. But still can't get the logic to get what I mentioned above.
Check this return only a specific country
<?php
$json = file_get_contents('university.json');
$universityArray = json_decode($json, true);
universities= array()
for($i=0; $i< count($universityArray); $i++)
{
if($universityArray[$i]["country"] == "Morocco")
universitises[] = $universityArray[$i];
}
var_dump($universitises);
?>
You can use alpha_two_code as index.
$indexed = [];
foreach($universityArray as $university){
$index = $university['alpha_two_code'];
if(!isset($indexed[$index])){
$indexed[$index] = [];
}
$indexed[$index][] = $university;
}
Now you will have universities seperated by alpha_two_code which you can directly access.
print_r($indexed['EG']);
Now as per the best and appropriate part, you may want to cache $indexed. You can create a directory for universities and save JSON encoded $indexed there.
You need to read the manual.
Try this:
$names = array();
foreach($universityArray as $u) {
if($u['alpha_two_code'] == 'EG' || $u['country'] == 'Egypt'){
$names[] = $u['name'];
}
}
print_r($names);
you can use the array_filter http://php.net/manual/en/function.array-filter.php function here with a callback. You can then use array_column http://php.net/manual/en/function.array-column.phpto grab just the 'name' column.
$json = file_get_contents('https://github.com/Hipo/university-domains-list/blob/master/world_universities_and_domains.json');
$universityArray = json_decode($json, true);
$filterBy = 'EG';
$newArray = array_filter($universityArray, function ($var) use ($filterBy) {
return ($var['alpha_two_code'] == $filterBy);
});
print_r($newArray);
$names = array_column($newArray, 'name');
print_r($names);

php JSON_DECODE for different data length

From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:
1. Query:
$names= $results[0]->name;
print_r($names);
First scenario:
[{"Name":"Mike"},{"Name":"Sean"}]
Second scenario:
{"Name":"Mike Smith","Spaces":"1"}
2. JSON_DECODE
$data = json_decode(stripslashes($names),true);
print_r($data);
First scenario:
Array
(
[0] => Array
(
[Name] => Mike
)
[1] => Array
(
[Name] => Smith
)
)
Second scenario:
Array
(
[Name] => Mike Smith
[Spaces] => 1
)
3. What I am trying to do: To put them into a string
$string = '';
for ($i=0; $i <sizeof($data) ; $i++){
$row = $data[$i];
$name = $row -> Name;
if(isset($row -> Spaces)){
$number = '(' . $row -> Spaces . ')';
}else{
$number = '';
};
$string .= $name . $number . ', ';
};
//Remove last comma
$refined = rtrim($string,', ');
print_r($refined);
4. ISSUE
The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".
How can I fix this?
Since you're passing true to the $assoc parameter of json_decode, $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)
However, you have basically the right idea on this line:
if(isset($row -> Spaces)){
For an array, that would instead by:
if(isset($row['Spaces'])){
You can do the same thing to see if you've got a name, or a list of names:
if(isset($row['Name'])) {
// In scenario B
echo $row['Name'];
// check for 'Spaces' etc
} else {
// In scenario A
foreach ( $row as $item ) {
echo $item['Name'];
}
}
Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.
Well I'll edit my answer for better understanding
$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';
$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);
if(is_object($json1))
{ echo 'json1 is object<br>'; } else
{ echo 'json1 is NOT object<br>'; }
if(is_object($json2))
{ echo 'json2 is object'; } else
{ echo 'json2 is NOT object'; }
http://php.net/manual/en/function.is-object.php

How can I rename some keys in a PHP array using another associative array?

Given a data array ...
$data_array = array (
"old_name_of_item" => "Item One!"
);
... and a rename array ...
$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);
... I would like to produce an output like this:
Array
(
[new_name_of_item] => Item One!
)
I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.
function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
foreach( $rename_array as $key => $replace ) {
if ($original_key == $key) {
$array[$replace] = $value;
unset($array[$original_key]);
}
}
}
return $array;
}
Does PHP offer built-in functions to help with this common problem? Thanks!
You only have to go through the array once:
function rename_keys($array, $rename_array) {
foreach ( $rename_array as $original_key => $value ) {
if (isset($array[$original_key])) {
$array[$rename_array[$original_key]] = $array[$original_key];
unset($array[$original_key]);
}
}
}
This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).
Edit: only replace if a corresponding element exists in $rename_array.
Edit 2: only goes through $rename_array
Second time today. This one is easier:
$data_array = array_combine(
str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

PHP: Finding Element Number in Multidimensional Array and Storing that value

I am using user user input into a form and then it will be searching through this array to see if their input is inside the array. So If a user searches for '45' I need to find its corresponding values in the array.
So if $myArray['Aames'][o] is 45 i need to also find $myArray['Names'][0] and so on. So i need a way to find the element number of '45' and store that number then print out the corresponding information.
$myArray = array
(
"Names"=>array
(
"John",
"Jane",
"Rick"
),
"Speciality"=>array
(
"Buisness",
"sales",
"marketing"
),
"Aames"=>array
(
"45",
"Some guy",
"Another guy"
)
);
$search = '45';
$key = array_search($search, $myArray['Aames']);
$name = $myArray['Names'][$key];
$speciality = $myArray['Speciality'][$key];
echo $name; //Outputs John
echo $speciality; //Outputs Business
You could generalize this a a bit with a function if you plan to apply it more generally.
function searchArray($query, $keyArray, $valuesArray){
$key = array_search($query, $keyArray);
$returnArray = array();
foreach($valuesArray as $arrKey=>$arrVal){
$returnArray[$arrKey] = $arrVal[$key];
}
return $returnArray;
}
$query is a string containing the value you are looking for in $keyArray and $valuesArray is an array of arrays that contain the values associated with the potential query strings.
Example: $userAttributes = searchArray('45', $myArray['Aames'], array('Names'=>$myArray['Names'], 'Speciality'=>$myArray['Speciality']));
$userAttributes should then be array('Names'=>'John', 'Speciality'=>'Buisness') [sic]

Categories