How to locate an array in a php object with no key - php

I have a database of zip codes from The Zip Code Database Project that came as a .csv file. I converted it to json and it has no key for each array, they look like this:
[
{
"zipcode": 35004,
"state abbreviation": "AL",
"latitude": 33.606379,
"longitude": -86.50249,
"city": "Moody",
"state": "Alabama"
}
]
I have figured out how to search all of the arrays and locate a matching zip code but I can't figure out how to make that search return data about the array that it found it in.
I can search like this:
$filename = './assets/data/zips.json';
$data = file_get_contents($filename);
$zipCodes = json_decode($data);
$inputZip = 55555;
foreach ($zipCodes as $location) {
if ($inputZip == $location->zipcode) {
echo "Success";
}
}
Can anyone tell me how I can use this search (or a better idea) to store the latitude and longitude associated with the searched zip code to two variables? I have wasted nearly my whole weekend on this so any and all help is greatly appreciated.
Also, I have no issue using the raw csv file to perform this function, I just couldn't get as far as I did with json.
Thanks everyone!

To find out the index of an array by a property of the array items, use array_column to get just the values of that column/property, then use array_search to find the index.
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object
https://3v4l.org/TAXQq

Based on your code:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
I should note that it seems you are doing something wrong because you don`t suppose to store your data like this and loop through array all the time.

To get the keys of an array that is filtered due to certain parameters that must be met you could use array_keys and array_filter.
For Example
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
Output
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
Try the above example in PHP Sandbox
To match your actual data structure.
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
Output
Array
(
[0] => 0
[1] => 1
)
Try the example in PHP Sandbox

Related

I have a json file with a list of associative arrays and I need to get it into a php indexed array that I can pull values out of

I cannot figure out how to take a list of associative arrays from a json file and convert it into a php indexed array of associative arrays, and then access the values nested in the associative arrays
Here is the json file
[
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
},
{
"homeTeam":"team1",
"homeScore":"00",
"awayTeam":"team2",
"awayScore":"00",
"gameProgression": "Not Started"
}
]
And the php code I have been trying to use
$gameFile = file_get_contents("currentGames.json");
$gameFileReady = json_decode($gameFile,true);
$gameArray = array_keys($gameFileReady);
if ($gameArray[0]['gameProgression'] != "Not Started") {
--code--
};
Thanks in advance
array_keys is just going to give you something like Array ( [0] => 0 [1] => 1 ) in this code. So it is unnecessary to achieve what you want.
Simply remove that line and do:
$gameFile = file_get_contents("currentGames.json");
$gameArray = json_decode($gameFile,true);
if (!isset($gameArray[0]['gameProgression'])) {
die('an error occurred');
}
if ($gameArray[0]['gameProgression'] != "Not Started") {
echo 'something';
};
The isset is just for good measure but doesn't change how you access the array item.

Extracting one object/group out of a JSON array and save it to a new file using PHP. I am hung up on the array part of the code

I have the following json structure I am trying to loop through and extract products from:
[]JSON
->{0}
-->[]username
-->[]avatar
-->[]rep
-->[]products
-->[]groups
-->[]feedbacks
-->[]online
-->[]staff
I am trying to ave only the products object into as a JSON file. This is the only result I need and delete/unset the rest:
[]JSON
->{0}
-->[]products
But I seem to be a bit confused, as I am not to familiar with how arrays work around PHP. Here is an angle I am currently trying:
<?php
$str = file_get_contents('test.json');
$json_decoded = json_decode($str,true);
foreach($json_decoded as $index){
unset($json_decoded[$index][???]);
}
file_put_contents('cleaned.json', json_encode($json_decoded));
?>
I added ??? where I am lost, this is about as far as I have gotten. I keep getting super confused. I know the structure will always be the same as above so I can technically just remove username,avatar,rep,groups,feedbacks,online, and staff seperatly. Which is just fine.
Here is an example of the json structure:
[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]
Thank you in advance, even a push in the right direction is much appreciated.
You could compose a new products array like this :
$products = [];
foreach($json_data as $value) {
$products[]['products'] = $value['products'];
}
file_put_contents('cleaned.json', json_encode($products));
This will results json objects like this :
[
{
"products": ["Big-01"]
},
{
"products": ["Big-02"]
},
{
"products": ["Big-03"]
},
{
"products": ["Big-04"]
},
{
"products": ["Big-05"]
}
]
From your snippet. try this.
<?php
$str = '[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]';
$json_decoded = json_decode($str,true);
foreach($json_decoded as $value) {
$products = $value['products'];
}
print_r( $products);
?>
output
Array
(
[0] => Big
)
Create a new array ($products), iterate over the old array, and set products as the one property instead of unseting every single array.
$products = [];
foreach ($json_decoded as $index) {
$products[$index] = [
'products' => $json_decoded[$index]['products']
];
}
file_put_contents('cleaned.json', json_encode($products));

Convert MySQL to Json ResultSet

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

How to change the array in order to make the desired JSON object in PHP?

I've an array titled $request as follows :
Array
(
[invite_emails] => suka#gmail.com, swat#gmail.com
[page_id] => 322
[ws_url] => http://app.knockknot.com/api/group/sendInvitation
)
After using json_encode($request) I got following output:
{
"invite_emails": "suka#gmail.com, swat#gmail.com",
"page_id": "322",
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
But actually I want the JSON object as follows :
{
"page_id": 322,
"invite_emails": [
"suka#gmail.com",
"swat#gmail.com"
],
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
How should I manipulate the array in PHP in order to get the above desired JSON object?
Please someone help me.
Split the list of emails using the comma:
$array["invite_emails"] = preg_split("#\s*,\s*#", $array["invite_emails"]);
I personally prefer using callback functions for readability and possibilities. To your purpose, array_walk should fit:
<?php
// reproducing array
$request = array(
"invite_emails" => "suka#gmail.com, swat#gmail.com",
"page_id" => 322,
"ws_url" => "http://app.knockknot.com/api/group/sendInvitation"
);
// callback finds a comma-separated string and explodes it...
array_walk($request, function (&$v,$k) {if ($k == 'invite_emails') $v = explode(", ", $v);});
// ... and then encode it to JSON
json_encode($request);
// testing
print_r($request);
OUTPUT:
{
"invite_emails":[
"suka#gmail.com",
"swat#gmail.com"
],
"page_id":322,
"ws_url":"http://app.knockknot.com/api/group/sendInvitation"
}
You are free to change the field if your needs changes, and even suppress it to be used with any field of the array.
Use PHP explode for example:
$array['invite_emails'] = explode(',',$array['invite_emails']);
To avoid spaces use preg_split (source):
$array['invite_emails'] = preg_split("/[\s,]+/", $array['invite_emails']);
This entry:
[invite_emails] => suka#gmail.com, swat#gmail.com
should be an array (currently, it is a string) in PHP, then in JSON it will look like you want it.

Json extra fields

I created this working code which is storing data from an api to a json file
based on yesterday's date.
$filedate = date('Y-m-d',strtotime("-1 days"));
$yesterday = date('Y-m-d 00:00',strtotime("-1 days"));
$today = date('Y-m-d 23:59',strtotime("-1 days"));
try{
$soccer=new XMLSoccer("API KEY");
$soccer->setServiceUrl("http://www.xmlsoccer.com/FootballData.asmx");
/* $result=$soccer->GetLiveScore();*/
$result=$soccer->GetFixturesByDateInterval(array( "startDateString"=> "$yesterday" ,"endDateString"=> "$today"));
var_dump($result);
$fp = fopen( "/var/www/public_html/domain/$filedate.json","w+");
fwrite($fp,json_encode($result));
fclose($fp);
}
catch(XMLSoccerException $e){
echo "XMLSoccerException: ".$e->getMessage();
}
The code above stores this json data in the file :
{
Match: [
{
Id: "346528",
Date: "2015-07-15T12:00:00+00:00",
League: "Chinese Super League",
Round: "19",
HomeTeam: "Guangzhou Evergrande",
HomeTeam_Id: "1108",
HomeGoals: "0",
AwayTeam: "Henan Jianye",
AwayTeam_Id: "1100",
AwayGoals: "0",
Time: "Not started",
Location: "Tianhe Stadium",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
{
Id: "346527",
Date: "2015-07-15T11:45:00+00:00",
League: "Chinese Super League",
Round: "19",
HomeTeam: "Shanghai Greenland Shenhua",
HomeTeam_Id: "1107",
HomeGoals: "0",
AwayTeam: "Beijing Guoan",
AwayTeam_Id: "1098",
AwayGoals: "0",
Time: "Not started",
Location: "Hongkou Football Stadium",
HomeTeamYellowCardDetails: { },
AwayTeamYellowCardDetails: { },
HomeTeamRedCardDetails: { },
AwayTeamRedCardDetails: { }
},
}
Right now I need to add some extra fields for each match, for example if HomeTeam = Real Madrid , add extra field HomeTeamShort = RMD etc. This should be done dynamically because I have to create IF's for each away and home team.
Somebody can help how can i do this ?
First you have to decode your json
$array = json_decode($result);
Get the Match array
$arr = $array->Match;
Now loop through all the objects (i.e.) and do whatever necessary
foreach($arr as $item) { //foreach element in $arr
//do whatever you want to do with that object
if($item->HomeTeam == "Real Madrid") {
$item->HomeTeamShort = "RMD";
}
}
print_r($arr); //Now $arr is the required result you wanted to have
//you can also convert your array back json
$arr2 = json_encode($arr);
Please let me know if you wanted something else and I will change my code to address your need.
Thank you.
* ADDITIONAL HELP WITH EXAMPLE *
Check if you have put the variables and arrays of object properly before running the loop. Since I can't see what you have really done in your code and what your line numbers are, I am pasting a full dummy code along with outputs, please compare it with your own code and you should be able to get the proper output.
<?php
//let's take an example json data
$result = '{"Match":
[
{"name":"Tom", "age":22},
{"name":"Jerry", "age":20},
{"name":"Hank", "age":25}
]
}';
$array = json_decode($result);
$arr = $array->Match;
Let's print the array once before processing
print_r($arr); //Array ( [0] => stdClass Object ( [name] => Tom [age] => 22 ) [1] => stdClass Object ( [name] => Jerry [age] => 20 ) [2] => stdClass Object ( [name] => Hank [age] => 25 ) )
Now do the loop thing and add whatever property you need to whichever object you want
foreach($arr as $item) { //foreach element in $arr
//do whatever you want to do with that object
if($item->name == "Jerry") {
$item->color = "Brown";
}
}
Now if you print the array again you will see Color Brown has been added to Jerry
print_r($arr); //Array ( [0] => stdClass Object ( [name] => Tom [age] => 22 ) [1] => stdClass Object ( [name] => Jerry [age] => 20 [color] => Brown ) [2] => stdClass Object ( [name] => Hank [age] => 25 ) )
Convert your array back json if you want
$arr2 = json_encode($arr);
Now, check the json, you will also see the Color Brown there against Jerry
var_dump($arr2); //string(92) "[{"name":"Tom","age":22},{"name":"Jerry","age":20,"color":"Brown"},{"name":"Hank","age":25}]"
?>
This is step by step analysis and explanation of this code. As you can see I am not getting any undefined object error. So, try copy pasting my above code and if you can replicate the same error, then it will be easy for me to understand what is causing your bug.
I have also made a PHPFiddle Link here, you can check the code and run it also there.
Thanks again.
Thank you for your help, don't solve my problem but make me progress(i'm getting close )
Maybe it's my mistake, because i don't provide some important things
So.. i test your code on phpfiddle and it works, and works mostly because you have the json directly on the code, in my project i need to open the file.json from the server, and with your code even adapting a few things , i get some errors, so ... i change your code a little bit :
<?php
$json_url = "http://getinstagoal.com/2015-07-20.json";
$json = file_get_contents($json_url);
$links = json_decode($json, TRUE);
foreach($links["Match"] as $key=>$val) {
if($val['HomeTeam'] == "Palmeiras") {
$val['HomeTeamshor'] = "RMD";
}
}
//you can also convert your array back json
$arr2 = json_encode($links);
//print the json, you will also see the Color Brown there against Jerry
var_dump($arr2); //string(92) "[{"name":"Tom","age":22},{"name":"Jerry","age":20,"color":"Brown"},{"name":"Hank","age":25}]"
?>
with that code i was able to get the right data, i try with some echo and etc.
however the file update didn't work even running php as root on the server, i check and "if" works (i test it with "echo") i try with file_put_content didn't work, the only way that i successfully do add something to the json file was creating and array of the content but that will rewrite the entire file. Any idea about that ?
Other thing, i will need to do "if" 8 items per match something like
if($val['HomeTeam'] == "Real Madrid") {
$val['HomeTeamshort'] = "RMD";
}
if($val['AwayTeam'] == "Barcelona") {
$val['AwayTeamshort'] = "FCB";
}
for more than 1300 (it should compare in the file, usually it's 20 games per day, not that much)
What is the most efficient way that i have to do this "ifs" to each match ?
Thank you #Suman

Categories