How insert array value in each index of another array in php? - 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);

Related

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

array_reduce to use dynamic variables pass in second function

I have below $test array
Array
(
[0] => Array
(
[quantity] => 3
[stock_id] => _PHONE
)
[1] => Array
(
[quantity] => 3
[stock_id] => 102
)
[2] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[3] => Array
(
[quantity] => 3
[stock_id] => 102
)
[4] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[5] => Array
(
[quantity] => 6
[stock_id] => _PHONE
)
[6] => Array
(
[quantity] => 2
[stock_id] => 102
)
)
and to sum same stock_id keys to one, i use below functions:
function sum($array, $key){
isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;
return $array;
};
//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum");
and the result went well like below:
$sum_same_stock_id:
Array
(
[_PHONE] => Array
(
[quantity] => 17
[stock_id] => _PHONE
)
[102] => Array
(
[quantity] => 8
[stock_id] => 102
)
)
So the question here is, I wanted to pass an dynamic keys values not just fixed values stock_id & quantity in sum function above. Have tried variety ways but still can't figured out the way. And can we put those functions into class as well?
Any advise is appreciated!
Maybe you can use the "use" function for the callback?
See https://www.php.net/manual/en/functions.anonymous.php

How to loop through subarray to see if value is return in string

Here is an example of an array that is output:
Array ( [CART] => Array ( [ITEMS] => Array ( [0] => Array ( [product_id] => 269194 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => 15 Top Hits for Easy Piano [product_code] => HL102668 [product_price] => 14.9900 [original_price] => 14.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) [1] => Array ( [product_id] => 266421 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => Whistle [product_code] => HD245839 [product_price] => 3.9900 [original_price] => 3.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) ) [LAST_UPDATED] => 1349829499 [NUM_ITEMS] => 2 ) [JustAddedProduct] => [CHECKOUT] => Array ( ) )
There is an array for each unique product (in this example there are 2 unique products.) Sometimes there will be just one, sometimes there could be 20 or more unique products.
The value that is important to me is [product_code]. You can see that in the first array, there is [product_code] => HL102668. In the second there is [product_code] => HD245839.
How can I check to see if 'HD' exists in any of the [product_code] values? If it does, I need to return false.
Thank you for your help!
Access your sub array :
$products = $array['CART']['ITEMS'];
Loop through your sub array :
foreach ($products as $product)
Check if HD exists in your product_code, with either simple strstr, or with regex using preg_match (if you are comfortable with it).
if (strstr($product['product_code'], "HD")) {
// Do your actions
}

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'];
}

retrieve matching elements in array

I have an array like this
Array
(
[35635d5ebdd938d6360e65a9e2484073] => Array
(
[rowid] => 35635d5ebdd938d6360e65a9e2484073
[id] => MYU_SC3
[qty] => 1
[price] => 4800
[name] => JAMB UTME Scratch Card
[service_image] => assets/img/jamb.jpg
[service_category] => cards
[subtotal] => 4800
)
[d8df18561040f3d9bd9868f5c5aaa7c2] => Array
(
[rowid] => d8df18561040f3d9bd9868f5c5aaa7c2
[id] => MYU_SC1
[qty] => 1
[price] => 1600
[name] => WAEC Scratch Card
[service_image] => assets/img/waec.jpg
[service_category] => cards
[subtotal] => 1600
)
[a4a751dd9a69824eb3abb6f49c7a7f61] => Array
(
[rowid] => a4a751dd9a69824eb3abb6f49c7a7f61
[id] => MYU_SC2
[qty] => 1
[price] => 1600
[name] => NECO Scratch Card
[service_image] => assets/img/neco.jpg
[service_category] => cards
[subtotal] => 1600
)
)
I want to retrieve the sub-arrays that match elements in another array
$card_skus = array("MYU_SC1","MYU_SC2","MYU_SC3");
Am looping through the main array
foreach ($this->cart->contents() as $key => $item) {
if(in_array($item['id'], $card_skus))
{
//Didn't know what to do at this point
}
}
How do i get this done, thanks for the help
I guess #nickb already answered in the comments, didnt see it while writing an answer.
Try this
$subArray = array();
foreach ($this->cart->contents() as $key => $item) {
if(in_array($item['id'], $card_skus))
{
//Didn't know what to do at this point
$subArray[] = $item;
}
}
Use $subArray now as per your requirement

Categories