Return A Single Variable From Array - php

i am using following script:
http://www.micahcarrick.com/php-zip-code-range-and-distance-calculation.html
To get the details for a ZIP code, I am using this:
$selected = $z->get_zip_details($zip);
$result = implode(",", $selected);
echo $result;
This returns all details of "$zip" :
32.9116,-96.7323,Dallas,Dallas,TX,Texas,214,Central
Could any1 help me to make the script return ONLY the city variable? The FAQ of the script, says the following:
get_zip_details($zip)
Returns the details about the zip code: $zip. Details are in the form of a keyed array. The keys are: latitude, longitude, city, county, state_prefix, state_name, area_code, and time_zone. All are pretty self-explanitory. Returns false on error.
Unfortunately I cant figure out how to get a single value (city). Would appreciate any help!
Thanks!

The functions is returning an array, so we have to store it in a variable.
$selected = $z->get_zip_details($zip);
Next, we can select the key which points to the city. The key is also called city.
echo $selected['city'];

Change this line
$result = implode(",", $selected);
To
$result = $selected['city'];

For future reference, implode() explode() etc. are array functions. So, if you're using them on something then you can print_r() it to see its structure.
If you had done print_r($selected); or var_dump($selected);, you would have gotten something like this as output:
Array ( [x] => 32.9116 [y] =>-96.7323 [city] => Dallas [state] => Texas [etc] => etc )
So you can see the keys of the array to know how to access the individual values.

Related

how to add values to an array without updating the array

I have two rows (longitude and latitude) in my MySQL table. I want to get the two rows into a 2-dimensional array such that when the values (longitude and latitude) change in the database the values will be added to the array. Not that the values will be updated.
while($mRow = $resultMarker->fetch_assoc()){
$myArrayForMarkers [] = $mRow['latitude'];
$myArrayForMarkers [] = $mRow['longitude'];
}
print_r($myArrayForMarkers);
The issue I have in the code above is that instead of the new values to be added from the database to the array, the values in the array are being updated. Any help would be appreciated.
As I said in the comments, the wording of your question makes little sens. For example, I don't undurstand what you mean by 'Not that the values will be updated.' nor how your array being 'updated' is different to 'the values will be added to the array'.
Please clarify your question, especially if my answer doesn't solve it so that those who will eventually come here while looking after a solution can understand if your issue is the same than theirs.
I get that you try to craft a 2-dimension array.
The code you provided produces 1-dimension arrays.
If you want to store your datas in a 2-dimension array, I only see two solutions :
Either your main array has two subarrays, each containing one type of data :
while ($mRow = $resultMarker->fetch_assoc()) {
$myArrayForMarkers['latitude'][] = $mRow['latitude'];
$myArrayForMarkers['longitude'][] = $mRow['longitude'];
}
or en
each entry of your array itself contains both information :
while ($mRow = $resultMarker->fetch_assoc()) {
$myArrayForMarkers[] = array('latitude' => $mRow['latitude'], 'longitude' => $mRow['longitude']);
}
That's the most I can do right now, since I don't understand the rest of your question.

Php array_rand() printing variable name

I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];

PHP: remove from string_array_A all strings contained in string_array_B

what I need is quite simple (for real php programmers :-D )
I have 2 strings array.
string_array_A contains a set of words contained in a post on my forum
string_array_B contains a set of words I don't want to be indexed in the search engine of my forum (just for db occupation reason).
So I would like to remove, from string_array_A, all the words contained in the string_array_B.
I would do 2 while loop, but maybe there are some high level functions I could use.
Thanks for your help !
array_diff() is probably what you're looking for:
$result = array_diff($string_array_A, $string_array_B);
This will return an array containing values from $string_array_A that are not present in $string_array_B.
Example:
$string_array_A = ['foo','bar','baz'];
$string_array_B = ['baz','bak','qux'];
$result = array_diff($string_array_A, $string_array_B);
print_r($result);
Output:
Array
(
[0] => foo
[1] => bar
)
Demo

Split PHP array and store in MySQL

I am really stuck at this part.. I have tried and searched but my mind is exploding because I can't figure it out.
I found this piece of code on the net, and I want to store every array on MySQL separately.
I need the code how to split this array and store each value in MySQL.
This is the output it has now:
Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => NL - Netherlands [state] => Saarland [town] => Schiffweiler )
But I want to store NL - Netherlands in e.g. MySQL table country.
Can someone please help me out?
Here is the code I found:
<?php
$ip='94.219.40.96';
print_r(geoCheckIP($ip));
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )
//Get an array with geoip-infodata
function geoCheckIP($ip)
{
//check, if the provided ip is valid
if(!filter_var($ip, FILTER_VALIDATE_IP))
{
throw new InvalidArgumentException("IP is not valid");
}
//contact ip-server
$response=#file_get_contents('http://www.netip.de/search?query='.$ip);
if (empty($response))
{
throw new InvalidArgumentException("Error contacting Geo-IP-Server");
}
//Array containing all regex-patterns necessary to extract ip-geoinfo from page
$patterns=array();
$patterns["domain"] = '#Domain: (.*?) #i';
$patterns["country"] = '#Country: (.*?) #i';
$patterns["state"] = '#State/Region: (.*?)<br#i';
$patterns["town"] = '#City: (.*?)<br#i';
//Array where results will be stored
$ipInfo=array();
//check response from ipserver for above patterns
foreach ($patterns as $key => $pattern)
{
//store the result in array
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
}
return $ipInfo;
}
?>
you can save each part of the array separetely into a mysql database, that shouldn't be the problem.
you can check out this site on how to access mysql from within php:
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
and the sql insert query should help:
mysql_query("INSERT INTO country (country) VALUES(".$ipInfo['country'].") ")
To me, the problem statement is a little vague.
If it's just a single unnested array as cited in the example, then what Petros advised should work, when you add the missing apostrophes so that you'll have the following statement:
mysql_query("INSERT INTO country (country) VALUES('".$ipInfo['country']."') ")
Note the added single-quote after the opening paren and before the closing paren.
My preference when writing SQL statement within PHP code block is by using the heredoc format like the following so that I can see what the SQL statement should be (and eyeball it to see if it's missing something or has typos):
$sql =<<<raw
INSERT INTO country (country)
VALUES ('%s');
raw;
mysql_query(sprintf($sql, $ipInfo['country']));
It's longer, but it helps make the code more legible to me.
If your data is an array of arrays, then you'll want to to create an array of countries first, then use the implode commands to join all the values.

Retrieve value from a Json Array

I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:
Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1
The code that achieves this is as follows:
$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";
$post_data_response = file_get_contents($post_data_URL);
$a_post_data_array=json_decode($post_data_response);
I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.
echo "**** -- " . $a_post_data_array[post_title] . "<br>";
Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.
There are multiple issues with your code:
First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
Then the result array is a list, and you have to access the first element as $data[0]
The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.)
And you need to put those array keys in quotes, like print $data[0]["postTitle"];
Turn up your error_reporting level for some development help.
echo "** -- " . $a_post_data_array[0]['post_title'];
try this PHP code:
//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);
// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');
// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";

Categories