Search array? Then get sub values? - php

I have an array that looks like
[products] => Array
(
[0] => stdClass Object
(
[order_product_id] => 91385
[order_id] => 5065
[nid] => 2140
[title] => Gi Treasure
[manufacturer] =>
[model] => giftcard
[qty] => 5
[cost] => 0.00000
[price] => 25.00000
[weight] => 0
[data] => Array
(
[gift_description] => HJello!
[gift_email] => dubccom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => Thesure
[gift_card] => 2130
[gift_price] => 25
[gift_qty] => 5
[gift_name] => Steveek
[module] => uc_product
[cert_code] => 8-x8mfqXyUYXze
)
[order_uid] => 1
)
[1] => stdClass Object
(
[order_product_id] => 91386
[order_id] => 5065
[nid] => 2140
[title] => Gift asure 2
[manufacturer] =>
[model] => giftcard
[qty] => 1
[cost] => 0.00000
[price] => 35.00000
[weight] => 0
[data] => Array
(
[gift_description] => Hello There!
[gift_email] => dubcaom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => The Holida
[gift_card] => 2134
[gift_price] => 35
[gift_qty] => 1
[gift_name] => Steven
[module] => uc_product
[cert_code] => 9-8xsxgDW9yrMq
)
[order_uid] => 1
)
)
And I want to get the data array from array of products where the order_product_id (so if it was 91385 I would get
[data] => Array
(
[gift_description] => Hello
[gift_email] => dubccom
[gift_sender] => Hello
[gift_sendDate] => 2011-10-25
[gift_title] => Thesure
[gift_card] => 2130
[gift_price] => 25
[gift_qty] => 5
[gift_name] => Steveek
[module] => uc_product
[cert_code] => 8-x8mfqXyUYXze
)
Any help how I could do so?

function search_products($id,$products)
{
$id = intval($id);
foreach($products as $product)
{
if($product->order_product_id == $id)
{
return($product->data);
}
}
return null;
}
An educated guess at what you're looking for. Call it like search_products(91385, $products). If it returns null, it hasn't found the product ID. I also added a call to intval so if you're relying on user input for this, it'll be an int regardless. If you already sanitize it to an int, this doesn't hurt.
EDIT: Misread original post. Updated from array syntax to object property syntax.

function data_by_order ($arr, $orderId) {
foreach ($arr as $item) { // Loop the array
if ($item->order_product_id == $orderId) { // Test this item for the right order id
return $item->data; // Return the data array
}
}
return FALSE; // Return false if we didn't find it
}
// Example usage:
$data = data_by_order($array,91385);
print_r($data);

$prod_data = false;
foreach ($products as $product)
{
if ($product->order_product_id == 91385)
{
$prod_data = $product->data;
break;
}
}
if ($prod_data) {
// knock yourself out
}
Quite similar to plain English, huh?

Related

Cannot get item from array

hi im new to api calling and i seem to have a problem with getting an item called price from my array. The following is the array that I am supposed to extract price from.
Array
(
[prodId] => ROC-PRD-2
[prodName] => iphone 6
[projectId] => 8
[categoryIds] => Array
(
[0] => ROC-CAT-1
)
[prodParentSku] => iph6a1
[prodMetaTitle] => iphone 6
[visible] => 1
[prodStatus] => 1
[modifiedDate] => 1443472415
[createDate] => 1443472193
[productImages] => Array
(
[0] => Array
(
[id] => 89
[imageName] => iphone-ipad hi res.png
[imagePath] => http://tos-staging-web-server-s3.s3.amazonaws.com/8/products/ROC-PRD-2/iphone_ipad_hi_res.png
[visible] => 1
[featured] =>
[modifiedDate] => 1443472390
[createDate] => 1443472390
)
[1] => Array
(
[id] => 90
[imageName] => ipad 2.jpg
[imagePath] => http://tos-staging-web-server-s3.s3.amazonaws.com/8/products/ROC-PRD-2/ipad_2.jpg
[visible] => 1
[featured] =>
[modifiedDate] => 1443472397
[createDate] => 1443472397
)
)
[pricing] => Array
(
[price] => 1000
[memberGroupPrices] => Array
(
)
)
)
I am able to get the product images information such as id, imagepath, using the following for loop
foreach ( $product['productImages'] as $key => $data){
foreach ($data as $key => $eachImage){
}
}
However for price my code is as follow:
foreach ( $product['pricing'] as $key => $price){
}
If i echo the $price i would get "1000Array"
If i echo $price['price'], nothing comes out.
You Dont need to look for $pricing as its its single;
$price = $product["pricing"]["price"];
$memberGroupPrices = $product["pricing"]["memberGroupPrices"];
Just print the price with out looping
$price = $array["pricing"]["price"];
Please check with this
foreach ( $product['pricing'] as $key => $price){
if($key=='price')
$price_val=$price;
}

How insert array value in each index of another array in php?

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);

PHP multi array get value

How can i get the value of a multi array.
So i need out of my array the [user_login] and i the [ID]
So something like echo $array[user_login] where [ID] is $variable[ID]
I need a solution which works without using echo $array[0][user_login]
Array
(
[0] => stdClass Object
(
[ID] => 15
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[1] => stdClass Object
(
[ID] => 28
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[2] => stdClass Object
(
[ID] => 13
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
[3] => stdClass Object
(
[ID] => 11
[user_login] => Loginname
[user_nicename] => Loginname
[user_email] => mail#mail.com
[user_url] => http://www.domain.com
[user_registered] => 2014-10-26 09:39:01
[user_activation_key] =>
[user_status] => 0
[display_name] => Test Inc
[logo] =>
)
)
You could loop through that array to create a new one:
$newArray = array();
foreach($array as $item){
$newArray[$item->ID] = $item;
}
Then with that you can access things using $newArray[$id]->whateveritem;
That's an array of objects, which is a bit different than an array of arrays (or multidimensional array).
You can loop through the array until you find the correct ID and then grab the user_login. SOmething like this
$myID = 15; //Id to search for
foreach ($array as $obj) {
if($obj->ID === $myID) {
echo $obj->user_login; //Or do something with it
}
}
Items in an array of objects are referenced like $object->member. An easy way to search through this array would be a simple foreach() loop. For example, to find the user with id 28, you would do:
foreach($array as $item) {
if ($item->ID == '28') {
echo 'Login is: ' . $item->user_login;
break;
}
}
Edit: Oops, Trivie beat me to it

Compare two arrays and remove unwanted items

I'm so close to this I could just scream.
Here's what I'm after. I have two arrays. The first one is a follows:
array("id", "txtLname", "txtFname");
The second is as follows:
Array
(
[0] => Array
(
[id] => 220
[RecordGUID] => 1233C9-1F7A15-E8A447-C56CB2-227C20-2829E0
[txtEmplid] => 5469857
[txtLname] => Jones
[txtFname] => Richard
[txtMname] =>
[txtEmail] => email address
[Reg_Pass] => umbra1234
[Reg_User] => user
[txtSecEmail] => user#gmail.com
[dtDOB] => 1979-02-28
[drpStatus] => STUDENT
[lstWaive] => 1
[ENTERED] => 2013-09-15 18:03:18
[Status] => 0
[Approvalcode] => 17dc8e7336f0e9fd3411a4d9617efe865c5744ac
[Approvaldate] => 2013-09-15 18:03:47
[Approved] => 1
)
[1] => Array
(
[id] => 221
[RecordGUID] => DD1E72-368879-68CFE2-E03010-ECE1B1-0974E9
[txtEmplid] => 4454688
[txtLname] => Mathews
[txtFname] => Richard
[txtMname] =>
[txtEmail] => user2#gmail.com
[Reg_Pass] => umbra1234
[Reg_User] => user
[txtSecEmail] => user3#gmail.com
[dtDOB] => 1979-02-28
[drpStatus] => STUDENT
[lstWaive] => 1
[ENTERED] => 2013-09-16 12:28:08
[Status] => 0
[Approvalcode] => 7182769e45dc38a3a747c4bdb128e2f0a8c658e4
[Approvaldate] =>
[Approved] => 0
)
[2] => Array
(
[id] => 222
[RecordGUID] => 40D8E7-04C600-30A829-8E26CC-498BBE-9D3DF6
[txtEmplid] =>
[txtLname] =>
[txtFname] =>
[txtMname] =>
[txtEmail] =>
[Reg_Pass] =>
[Reg_User] =>
[txtSecEmail] =>
[dtDOB] => 1979-02-28
[drpStatus] => STUDENT
[lstWaive] => 1
[ENTERED] => 2013-09-16 12:28:24
[Status] => 0
[Approvalcode] => 8d2c33f7b7d6ef620811dbc4358e8103346bfb59
[Approvaldate] =>
[Approved] => 0
)
)
All I need is to loop through the second array and remove the items that do not match the first. The result would be as follows:
Array
(
[0] => Array
(
[id] => 220
[txtLname] => Method
[txtFname] => Richard
)
[1] => Array
(
[id] => 221
[txtLname] => Method
[txtFname] => Richard
)
[2] => Array
(
[id] => 222
[txtLname] => Method
[txtFname] => Richard
)
)
Here's what I've done so far.
foreach ($r as $reg) {
foreach($reg as $k => $v) {
if ($k == !in_array($k, $f)) {
echo $reg[$k];
}
}
}
The echo response I get is a listing of all of the data from the first array, minus the fields that are in the first array. So, it is removing items that
I want removed, but I can't seem to get it into the proper format.
Thanks in advance for your help.
$arr1 = array("id"=>1, "txtLname"=>1, "txtFname"=>1)
$result = array();
// $arr2 = array 2 (check your code)
foreach ($arr2 as $el) {
$result[] = array_intersect_key($el, $arr1);
}
var_dump($result);
replace echo $reg[$k]; with unset($reg[$k]);

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