partial search in multidimensional array - php

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.

Related

Warning error on JSON decode

I'm getting a warning on a json decode foreach within a foreach (although the code works which is strange) the warning is: Warning: Invalid argument supplied for foreach() it is referring to this line: foreach ($value as $val) {
Here is the JSON response:
Array
(
[ACTION] => avail.datacenters
[DATA] => Array
(
[0] => Array
(
[LOCATION] => Dallas, TX, USA
[DATACENTERID] => 2
[ABBR] => dallas
)
[1] => Array
(
[LOCATION] => Fremont, CA, USA
[DATACENTERID] => 3
[ABBR] => fremont
)
[2] => Array
(
[LOCATION] => Atlanta, GA, USA
[DATACENTERID] => 4
[ABBR] => atlanta
)
[3] => Array
(
[LOCATION] => Newark, NJ, USA
[DATACENTERID] => 6
[ABBR] => newark
)
[4] => Array
(
[LOCATION] => London, England, UK
[DATACENTERID] => 7
[ABBR] => london
)
[5] => Array
(
[LOCATION] => Tokyo, JP
[DATACENTERID] => 8
[ABBR] => tokyo
)
[6] => Array
(
[LOCATION] => Singapore, SG
[DATACENTERID] => 9
[ABBR] => singapore
)
[7] => Array
(
[LOCATION] => Frankfurt, DE
[DATACENTERID] => 10
[ABBR] => frankfurt
)
[8] => Array
(
[LOCATION] => Tokyo 2, JP
[DATACENTERID] => 11
[ABBR] => shinagawa1
)
)
[ERRORARRAY] => Array
(
)
)
My foreach code:
$randDCID = array();
foreach ($linodeRegions as $value) {
foreach ($value as $val) {
echo $val['DATACENTERID'] . "<br />";
$randDCID[] = $val['DATACENTERID'];
}
}
Can anyone see the issue on the warning (although it is outputting the desired results).
The error is probably coming from the ACTION index and the corresponding value(which is string) of the array. Assuming the fact that $linodeRegions in your original array, there's no need to create nested loops in this case, simply use a foreach loop like this:
$randDCID = array();
foreach ($linodeRegions['DATA'] as $value) {
echo $value['DATACENTERID'] . "<br />";
$randDCID[] = $value['DATACENTERID'];
}

How to find the lowest value of an array?

The result of print_r($data['SearchAvailResponse']['Hotel']) :
Array
(
[0] => Array
(
[HotelNo] => 1
[HCode] => IDJKT_00085
[Name] => Cebu Grand Hotel
[Currency] => USD
[TotalRate] => 56
)
[1] => Array
(
[HotelNo] => 2
[HCode] => IDJKT_00094
[Name] => Best Western Plus Lex Cebu
[Currency] => USD
[TotalRate] => 65
)
[2] => Array
(
[HotelNo] => 3
[HCode] => IDJKT_00102
[Name] => Best Western Sand Bar
[Currency] => USD
[TotalRate] => 93
)
[3] => Array
(
[HotelNo] => 4
[HCode] => IDJKT_00106
[Name] => Goldberry Suites & Hotel
[Currency] => USD
[TotalRate] => 51
)
)
TotalRate tag is hotel price
I want to find the lowest price of all hotels
How do I find the lowest price of all hotels?
Any help much appreciated
Cheers
$cheapesthotel = array();
foreach($data['SearchAvailResponse']['Hotel'] as $hotel){
if($cheapesthotel == array()){
$cheapesthotel = $hotel;
} elseif ($hotel['TotalRate'] < $cheapesthotel['TotalRate']){
$cheapesthotel = $hotel;
}
}
function getMin($array)
{
$currentMin = 10000;
$minObject = Array();
foreach($array as $val)
{
if($val[totalRate] < $currentMin)
{
$minObject = $val;
}
}
return minObject;
}

I am trying to load variables in an array

I am using an api that returns an array, I am trying to get set the variables of each condition that i need but cannot figure it out.
Here is the array:
Array
(
[0] => Array
(
[sl_translate] => description,descriptionPlain,category
[id] => 65392
[slug] => crystal-coma
[name] => Crystal Coma
[symbol] => Crc
[category] => Sativa
[description] => <p class="p1">Crystal Coma is a rare sativa-dominant hybrid from California that induces deep, trance-like effects. Its name foreshadows the debilitating relaxation to come, a long-lasting calm that shuts off mental overactivity. Pastel green breaks through this sativa’s thick blanket of crystal trichomes that contributes to its staggeringly high THC content of up to 26 percent. Crystal Coma’s genetics are long lost, but myth has it that the origins lie in <span class="s1">Cheese</span> and <span class="s1">Skunk #1</span>. Anxiety, PTSD, pain, and sleeplessness are no match for Crystal Coma’s potency, a medicine that is highly recommended for nighttime use. Crystal Coma took 3rd place in the 2014 L.A. Cannabis Cup.</p>
[descriptionPlain] => Crystal Coma is a rare sativa-dominant hybrid from California that induces deep, trance-like effects. Its name foreshadows the debilitating relaxation to come, a long-lasting calm that shuts off mental overactivity. Pastel green breaks through this sativa’s thick blanket of crystal trichomes that contributes to its staggeringly high THC content of up to 26 percent. Crystal Coma’s genetics are long lost, but myth has it that the origins lie in Cheese and Skunk #1. Anxiety, PTSD, pain, and sleeplessness are no match for Crystal Coma’s potency, a medicine that is highly recommended for nighttime use. Crystal Coma took 3rd place in the 2014 L.A. Cannabis Cup.
[aka] =>
[rating] => 5
[reviewCount] => 6
[flavors] => Array
(
[0] => Array
(
[name] => Lemon
[score] => 40
)
[1] => Array
(
[name] => Pungent
[score] => 26.25
)
[2] => Array
(
[name] => Cheese
[score] => 20
)
[3] => Array
(
[name] => Flowery
[score] => 20
)
[4] => Array
(
[name] => Skunk
[score] => 20
)
)
[effects] => Array
(
[0] => Array
(
[name] => Euphoric
[score] => 105
)
[1] => Array
(
[name] => Relaxed
[score] => 92.5
)
[2] => Array
(
[name] => Energetic
[score] => 85
)
[3] => Array
(
[name] => Uplifted
[score] => 78.75
)
[4] => Array
(
[name] => Happy
[score] => 65
)
)
[symptoms] => Array
(
[0] => Array
(
[name] => Depression
[score] => 51.25
)
[1] => Array
(
[name] => Stress
[score] => 51.25
)
[2] => Array
(
[name] => Pain
[score] => 38.75
)
[3] => Array
(
[name] => Fatigue
[score] => 26.25
)
[4] => Array
(
[name] => Lack of Appetite
[score] => 25
)
)
[conditions] => Array
(
[0] => Array
(
[name] => ADD/ADHD
[score] => 32.5
)
[1] => Array
(
[name] => Anxiety
[score] => 32.5
)
[2] => Array
(
[name] => PTSD
[score] => 32.5
)
[3] => Array
(
[name] => Asthma
[score] => 20
)
[4] => Array
(
[name] => Arthritis
[score] => 6.25
)
)
[negatives] => Array
(
[0] => Array
(
[name] => Dizzy
[score] => 6.25
)
[1] => Array
(
[name] => Dry Eyes
[score] => 6.25
)
[2] => Array
(
[name] => Dry Mouth
[score] => 6.25
)
)
[articlesAvailable] => 1
[photos] => Array
(
[0] => Array
(
[uploaded] => /Date(1398397718127)/
[thumb] => http://leafly.blob.core.windows.net/reviews/crystal-coma_100x100_255e.jpg
[fullsize] => http://d3odcnigi1nnzz.cloudfront.net/cdn/strain-photo/132654/b/crystal-coma_825x550_4e1f.jpg
)
)
[popularCities] => Array
(
[0] => Colorado Springs,CO
[1] => Vancouver,BC
[2] => North Palm Springs,CA
[3] => Temecula,CA
[4] => Torrance,CA
)
[permalink] => http://www.leafly.com/sativa/crystal-coma
[starImage] => //d3odcnigi1nnzz.cloudfront.net/stars/5/240
[testGraph] =>
[weakDescription] =>
[parents] => Array
(
)
[growInfo] => Array
(
[difficulty] =>
[preferredMedium] =>
[floweringDays] => 0
[outdoorFinish] =>
[height] =>
[averageYield] =>
[environment] =>
[growNotes] =>
)
)
)
I am trying to get the effects, symptoms, negatives and popular cities extracted out of the array.
here is what I have tried so far:
$strain = $_REQUEST['strain'];
//init curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://data.leafly.com/strains/".$strain); //change the strain dynamically of course for your app
curl_setopt($ch,CURLOPT_HTTPHEADER,array('APP_ID:'.$appID,'APP_KEY:'.$appKEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
//Clean it into an php array object and set var
$cleaned_response = array(json_decode($output,true));
//Set Variables
foreach($cleaned_response as $i)
{
$titles=$i['name'];
$category = $i['category'];
$description = $i['description'];
$rating = $i['rating'];
//Convert this array to variables
foreach($i['effects'] as $a=>$value){
$effects = '<li>'. $a[$value] .'</li>'.PHP_EOL;
}
foreach($i['symptoms'] as $a=>$value){
$symptoms = '<li>'. $a[$value] .'</li>'.PHP_EOL;
}
foreach($i['negatives'] as $a=>$value){
$negatives = '<li>'. $a[$value] .'</li>'.PHP_EOL;
}
foreach($i['popularCities'] as $a=>$value){
$popularCities = '<li>'. $a[$value] .'</li>'.PHP_EOL;
}
}
but it is not returning the results.
Take one example
foreach($i['effects'] as $a=>$value){
$effects = '<li>'. $a[$value] .'</li>'.PHP_EOL;
}
That is an incorrect loop to extract effects. $a is the key of each effect and $value is the array that contains name and score. So you cant say $a[$value];. It should be
foreach($i['effects'] as $a=>$value){
$effects. = '<li>'. $value['score'] .'</li>'.PHP_EOL; // or name
^
}
fix that for all your loops and you're good
Two problems i can see at first look in this code:
IF this is your whole file, you are not outputting the values in any way in order for them to display to the browser,
You are overwriting the variables each time instead of appending to them (use .=)
You are using the key=>value pair wrong, ie to take the name of the recipe you should do something similar to:
$effects = "";
foreach($i['effects'] as $a=>$value){
$effects .= '<li>'. $value['name'] .'</li>'.PHP_EOL;
}
echo $effects;
Although this is untested code, it should work as $value inside the loop is still an array and you'll need to add the name or other proper index to get the needed value.
define variables out side the main foreach loop
Note that [popularCities] is not a multidimentional array
$effects = $symptoms = $negatives = $popularCities = "";
//foreach($cleaned_response as $i)
foreach($i['effects'] as $a=>$value){
$effects .= '<li>'. $value['name'] .'</li>';
$effects .= '<li>'. $value['score'] .'</li>'.PHP_EOL;
}
foreach($i['symptoms'] as $a=>$value){
$symptoms .= '<li>'. $value['name'] .'</li>';
$symptoms .= '<li>'. $value['score'] .'</li>'.PHP_EOL;
}
foreach($i['negatives'] as $a=>$value){
$negatives .= '<li>'. $value['name'] .'</li>';
$negatives .= '<li>'. $value['score'] .'</li>'.PHP_EOL;
}
foreach($i['popularCities'] as $a=>$value){
$popularCities .= '<li>'. $value .'</li>'.PHP_EOL;
}

Multidimensional for google chart

I been playing around with google chart for my project, and somehow I'm still cant figure out displaying multidimensional array (from database).
print_r() output:
Array
(
[0] => Array
(
[year] => 2000
[value] => 2766
[typeName] => Oil
)
[1] => Array
(
[year] => 2000
[value] => 3098
[typeName] => Gas
)
[2] => Array
(
[year] => 2000
[value] => 269814
[typeName] => Coal
)
[3] => Array
(
[year] => 1999
[value] => 2836
[typeName] => Oil
)
[4] => Array
(
[year] => 1999
[value] => 3150
[typeName] => Gas
)
[5] => Array
(
[year] => 1999
[value] => 257561
[typeName] => Coal
)
);
as google chart required data format, I want it to be something like this:
['Year' , 'Oil', 'Gas', 'Coal']
["2000", 2766, 3098, 269814],
["1999" 2836, 3150, 257561]
Can someone help me how to play around with the multidimensional?
Thanks!
You shuld convert this data into json. Just parse in this way to get the desired structure O(n)
$headers = array("year" => 0, "oil" => 1, "gas" => 2, "coal" => 3);
$response[] = array_map("ucfirst",array_keys($headers));
foreach($orig_array as $k => $item) {
$temp_data[$item['year']][0] = (string) $item['year'];
$temp_data[$item['year']][$headers[$item['typeName']]] = $item['value'];
if(4==count($temp_data[$item['year']])) $response[] = $temp_data[$item['year']];
}
$json_data = json_encode($response);
echo($json_data);

Get value in mutli array

How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}

Categories