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'];
}
Related
it seems I cant get this one.
I am trying to get a loop from this json output. My aim is the variation values to be separated from the group:
Array
(
[response_description] => 000
[content] => Array
(
[ServiceName] => Gotv Payment
[serviceID] => gotv
[convinience_fee] => N0.00
[varations] => Array
(
[0] => Array
(
[variation_code] => gotv-lite
[name] => GOtv Lite N410
[variation_amount] => 410.00
[fixedPrice] => Yes
)
[1] => Array
(
[variation_code] => gotv-max
[name] => GOtv Max N3,600
[variation_amount] => 3600.00
[fixedPrice] => Yes
)
[2] => Array
(
[variation_code] => gotv-jolli
[name] => GOtv Jolli N2,460
[variation_amount] => 2460.00
[fixedPrice] => Yes
)
[3] => Array
(
[variation_code] => gotv-jinja
[name] => GOtv Jinja N1,640
[variation_amount] => 1640.00
[fixedPrice] => Yes
)
[4] => Array
(
[variation_code] => gotv-lite-3months
[name] => GOtv Lite (3 Months) N1,080
[variation_amount] => 1080.00
[fixedPrice] => Yes
)
[5] => Array
(
[variation_code] => gotv-lite-1year
[name] => GOtv Lite (1 Year) N3,180
[variation_amount] => 3180.00
[fixedPrice] => Yes
)
)
)
)
I tried this and I got the values, but they are in a group, I need them separated in a loop of as in the json output for 0, 1, etc
Here is what I tried:
$array = json_decode($result, true);
//echo '<pre>';print_r(json_decode($result,TRUE));
foreach ($array as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $varations) {
foreach($varations as $key => $loop) {
foreach($loop as $key => $value) {
echo $value;
echo "<br><br>";
}
}
}
}
And got this:
gotv-lite
GOtv Lite N410
410.00
Yes
gotv-max
GOtv Max N3,600
3600.00
Yes
gotv-jolli
GOtv Jolli N2,460
2460.00
gotv-lite
GOtv Lite N410
410.00
Yes
gotv-max
GOtv Max N3,600
3600.00
Yes
gotv-jolli
GOtv Jolli N2,460
2460.00
Please someone help your friend. Thanks
I am having two arrays, in that i need to insert the each index of last key and value of another array keys, values in php. My sample arrays are given below. I am using codeigniter framework.
First array:
Array
(
[0] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Bacardi Rum
[quantity] => 1
[unit_price] => 25.00
[inv_discount] => 0.00
[salesman_id] => 25,27
)
[1] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Baileys
[quantity] => 1
[unit_price] => 15.00
[inv_discount] => 0.00
[salesman_id] => 28,29
)
)
Second array:
Array
(
[0] => 140140,150150
[1] => 151151,05180518
)
And i need the o/p :
Array
(
[0] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Bacardi Rum
[quantity] => 1
[unit_price] => 25.00
[inv_discount] => 0.00
[salesman_id] => 25,27
[salesman] => 140140,150150
)
[1] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Baileys
[quantity] => 1
[unit_price] => 15.00
[inv_discount] => 0.00
[salesman_id] => 28,29
[salesman] => 151151,05180518
)
)
Can any one help me, give some ideas to solve this.
In this case, you have an array of objects (stdClass type) and one other array only. Answering your question you just have to do the code as shown below.
foreach ($secondArray as $key => $value) {
$firstArray[$key]->salesman = $value;
}
or
foreach ($firstArray as $key => $object) {
$object->salesman = $firstArray[$key];
}
foreach($arrA as $key=>$val){
$arrA[$key]['salesman'] = $arrB[$key];
}
As long as both arrays will be same size, array_map will be suitable:
$resultArray = array_map(function ($rowA, $rowB) {
$rowA->salesman = $rowB;
return $rowA;
}, $firstArray, $secondArray);
I have an array $products that looks like this
Array
(
[services] => Array
(
[0] => Array
(
[id] => 1
[icon] => bus.png
[name] => Web Development
[cost] => 500
)
[1] => Array
(
[id] => 4
[icon] => icon.png
[name] => Icon design
[cost] => 300
)
)
)
I am trying to delete the part of array that matches [id] => 1 and for this I am using the following code
$key = array_search('1', $products);
unset($products['services'][$key]);
However it is not working and I am not getting any error either.
What am i doing wrong?
This should work for you:
$key = array_search('1', $products["services"]);
//^^^^^^^^^^^^ See here i search in this array
unset($products['services'][$key]);
print_r($products);
Output:
Array ( [services] => Array ( [1] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
And if you want to reindex the array, so that it starts again with 0 you can do this:
$products["services"] = array_values($products["services"]);
Then you get the output:
Array ( [services] => Array ( [0] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
//^^^ See here starts again with 0
This will loop through $products['services'] and delete the array whose 'id' key has value 1. array_values just re-indexes the array from 0 again.
foreach($products['services'] as $key => $service)
{
if($product['id'] == 1)
{
unset($products['services'][$key]);
array_values($products['services']);
break;
}
}
This code builds an array:
$size = sizeof($include_quotes);
for ($i=0; $i<$size; $i++) {
$quotes = $GLOBALS[$include_quotes[$i]]->quote($method);
if (is_array($quotes)) $quotes_array[] = $quotes;
}
}
If i
print_r($quotes_array);
i get the following:
Array ( [0] => Array ( [id] => advshipper [methods] => Array ( [0] => Array ( [id] => 1-0-0 [title] => Trade Shipping [cost] => 20 [icon] => [shipping_ts] => [quote_i] => 0 ) [1] => Array ( [id] => 2-0-0 [title] => 1-2 working days [cost] => 3.2916666666667 [icon] => [shipping_ts] => [quote_i] => 1 ) [2] => Array ( [id] => 4-0-0 [title] => 2-3 working days [cost] => 2.4916666666667 [icon] => [shipping_ts] => [quote_i] => 2 ) [3] => Array ( [id] => 8-0-0 [title] => Click & Collect [cost] => 0 [icon] => [shipping_ts] => [quote_i] => 3 ) ) [module] => Shipping [tax] => 20 ) )
In some circumstances, I only want the data in field 0 to be passed onto the next part of the code. However, using
$sliced_quotes_array = array_slice($quotes_array,0,1);
Still returns all the results.
What is the correct method to get just:
Array ( [0] => Array ( [id] => advshipper [methods] => Array ( [0] => Array ( [id] => 1-0-0 [title] => Trade Shipping [cost] => 20 [icon] => [shipping_ts] => [quote_i] => 0 )
Any help greatly appreciated because i have tried numerous different ways and no luck yet.
Using the following still returns the same results
$testarray = array(0 => $quotes_array[0]);
print_r($testarray);
Why not just use the array constructor and explicitly include what you need:
array(0 => $quotes_array[0]);
Here is your array:
When you are saying " I only want the data in field 0 to be passed onto the next part of the code", you meant that you only want this data to be passed next, right? :
Array (
[0] => Array (
[id] => advshipper
[module] => Shipping
[tax] => 20
)
)
Is this what you want?
$newArray = array();
foreach ($quotes_array[0] as $items)
{
if (!is_array($items))
{
$newArray[] = $items;
}
}
$newArray will contain that data.
UPDATE
Okay, gotcha.
You can just use this:
$newArray = $quotes_array[0]['methods'][0];
Having done some reading on arrays and after a bit of trial, i found a solution to my problem.
I used:
unset($quotes_array[0]['methods'][1]);
By changing the index number after methods i was able to drop any shipping options i didn't require, whilst still maintaining the functionality.
I am attempting to use a recursive function to search through a multidimensional array, such as the one below, to find certain values, i.e. people who went to certain school, majored in a certain subject, hold a certain job title, etc. In case your wondering, this array is output from the Facebook Graph API. In reality there are more than 3 offset arrays, depending on the number of friends a user has, it could be in the thousands.
Here's a solution I tried with very little knowledge of recursive functions (my first thought was to use in_array before I found out it didn't work for md arrays):
So to give you an idea of how the md array below works, check out this snippet of code:
$friend = $fqlResult[0]['name'];
echo "$friend";
*The output would be "BLANK" since I deleted the person's name.
$data = $fqlResult;
$collegemajor = (isset($value['education'][0]['concentration'][0]['name'])) ? $value['education'][0]['concentration'][0]['name'] : null ;
$major = "Business Administration";
if (isset($collegemajor)) {
foreach($data as $key=> $value) {
if ($value($collegemajor) == $major) {
echo "User $key is majoring in $major";
}
}
}
So here is the multidimensional array referenced above. In this example, I want to pull the names of all of the user's friends who majored in Business Admin. in college. As you can see from this snippet, there aren't any (I think) but in the long version of the array, there are plenty. The code above produces no output and I'm lost as to how to make it work. Any help would be greatly appreciated.
Array
(
[0] => Array
(
[name] => BLANK
[education] =>
[work] =>
)
[1] => Array
(
[name] => BLANK
[education] => Array
(
[0] => Array
(
[school] => Array
(
[id] => 108087985890571
[name] => St. Andrew's School
)
[year] => Array
(
[id] => 138383069535219
[name] => 2005
)
[type] => High School
)
[1] => Array
(
[school] => Array
(
[id] => 20697868961
[name] => Boston University
)
[concentration] => Array
(
[0] => Array
(
[id] => 108654845832522
[name] => Business Administration
)
)
[type] => College
)
[2] => Array
(
[school] => Array
(
[id] => 108289315859633
[name] => University of Miami
)
[year] => Array
(
[id] => 138879996141011
[name] => 2013
)
[type] => Graduate School
)
)
[work] => Array
(
)
)
[2] => Array
(
[name] => BLANK
[education] => Array
(
[0] => Array
(
[school] => Array
(
[id] => 115444241803885
[name] => Saint Andrews High School
)
[year] => Array
(
[id] => 137616982934053
[name] => 2006
)
[type] => High School
)
[1] => Array
(
[school] => Array
(
[id] => 112033702149888
[name] => Boca Raton High
)
[year] => Array
(
[id] => 137616982934053
[name] => 2006
)
[type] => High School
)
[2] => Array
(
[school] => Array
(
[id] => 108087985890571
[name] => St. Andrew's School
)
[type] => High School
)
[3] => Array
(
[school] => Array
(
[id] => 107573562605861
[name] => Duke University
)
[concentration] => Array
(
[0] => Array
(
[id] => 104045469631213
[name] => Political science
)
)
[type] => College
)
)
[work] =>
)
[4] => Array
(
[uid] => 1234567
[name] => BOB NO ONE
[education] => Array
(
[0] => Array
(
[school] => Array
(
[id] => 106039752760627
[name] => Berwick Academy
)
[year] => Array
(
[id] => 137616982934053
[name] => 2006
)
[type] => High School
)
[1] => Array
(
[school] => Array
(
[id] => 108087985890571
[name] => St. Andrew's School
)
[type] => High School
)
[2] => Array
(
[school] => Array
(
[id] => 105690226130720
[name] => Northeastern University
)
[concentration] => Array
(
[0] => Array
(
[id] => 108654845832522
[name] => Business Administration
)
)
[type] => College
[classes] => Array
(
[0] => Array
(
[id] => 189873264368867
[name] => 2011
)
)
)
)
There's really no need for recursion for something like this, considering the depth of the tree is always fixed and the structure is known. Using some nested loops would do the trick:
$friends = $fqlResult;
$friends_BA = array();
foreach ($friends as $friend) {
if (is_array($friend['education'])) {
foreach ($friend['education'] as $school) {
if (isset($school['concentration'])) {
foreach ($school['concentration'] as $concentration) {
if (strpos(strtolower($concentration['name']), 'business') !== false) {
$friends_BA[] = $friend;
continue 3; // skip to the next friend
}
}
}
}
}
}
var_dump($friends_BA);
You want a function that will find a specific value on a specific field in the array,
function arraySearch($key, $value, $array){
$flag = FALSE;
foreach($array as $result){
if(arraySearch($key, $value, $result)){
$flag = TRUE
}elseif(isset($result[$key] && $result[$key] == $value){
$flag = TRUE;
}
}
return $flag
}
to improve performance rather than setting $flag to true, you could return true as it will stop the execution of the function and prevent it from continuing to search the array.
Call it like so
foreach($fqlResult as $result){
if(arraySearch('concentration', 'Business Administration', $result)){
//You have found a user you are looking for, echo $result['name'] or do what you want with the result.
}
}