PHP Array Setup from Variable - php

I have a list of items I want to feed to an API via an array but it is built from a separate object. I was thinking I could loop through the items in the object to construct a variable I could then feed to the array but something is disconnected. This is probably easier to see than it is to explain.
The code I am using is this:
//Set up the parser object
$parser = new XMLParser($xml);
$parser->Parse();
$skuList = '';
// Pull the inventory of the requested SKUs from Magento for comparison later
foreach($parser->document->product as $product)
{
$skuList .= "'" . $product->sku[0]->tagData . "',";
}
echo $skuList;
print_r( $proxy->call($sessionId, 'product_stock.list', array(array($skuList))));
If I run this at the command line I get
'1DAFPOT5','8GAIL','26BULK30',Array
(
)
Now if I change the print_r line by putting the contents of the variable directly in the call like this
print_r( $proxy->call($sessionId, 'product_stock.list', array(array('1DAFPOT5','8GAIL','26BULK30', ))));
I get this output which is what I am looking for
'1DAFPOT5','8GAIL','26BULK30',Array
(
[0] => Array
(
[product_id] => 2154
[sku] => 26BULK30
[qty] => 19.0000
[is_in_stock] => 1
)
[1] => Array
(
[product_id] => 2255
[sku] => 8GAIL
[qty] => 16.0000
[is_in_stock] => 1
)
[2] => Array
(
[product_id] => 2270
[sku] => 1DAFPOT5
[qty] => 23.0000
[is_in_stock] => 1
)
)
Am I constructing the variable incorrectly or do I need to feed it to the array differently?

$skuList looks like an array, but is still a string.
You have to do this after foreach loop:
$skuList = explode(',',$skulist);
Or, better, make skuList an array since beginnig:
$skuList = array();
foreach($parser->document->product as $product)
{
$skuList[] = $product->sku[0]->tagData;
}
print_r( $proxy->call($sessionId, 'product_stock.list', array($skuList)));
http://www.php.net/manual/en/function.explode.php

Related

php cannot use API data

I send a request and get back JSON, so I convert that JSON to an array, but I cannot use the array with my php:
$all_transactions_raw = file_get_contents("xxx");
$all_transactions = json_decode( $all_transactions_raw );
foreach ( $all_transaction as $transaction ) {
echo $transaction;
}
First part of the very long output:
Array (
[data] => Array (
[transactions] => Array (
[0] => Array (
[id] => t1rtn-gsjkadfv
[date] => 2017-11-01
[amount] => -8847
[memo] =>
[cleared] => reconciled
[approved] => 1
[flag_color] =>
why does the above code not print a list of transactions given by the api request?
when I use print_r( $all_transactions ); I can print out a long string of what looks like an array but I cannot access the data contained in it as separate chunks. Am I missing something?
i guess you are missing these keys in foreach
$all_transactions_raw = file_get_contents("xxx");
$all_transactions = json_decode( $all_transactions_raw );
foreach ( $all_transaction['data']['transactions'] as $transaction ) {
echo $transaction;
}

Cycling an array and delete item

I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}

php array merge with value of parent array

I need to merge an array with value of parent array.
$testArr=unserialize('a:6:{s:5:"queue";a:2:{i:6;s:1:"5";i:5;s:1:"2";}s:3:"sum";a:2:{i:6;s:3:"765";i:5;s:3:"2.1";}s:7:"sumAccD";a:2:{i:6;s:3:"543";i:5;s:3:"3.1";}s:7:"sumAccC";a:2:{i:6;s:2:"54";i:5;s:3:"3.3";}s:7:"comment";a:2:{i:6;s:12:"test comment";i:5;s:6:"111222";}s:3:"yt0";s:0:"";}');
$ret = array();
foreach ($testArr as $pkey => $pval) {
if (is_array($pval)) {
foreach ($pval as $pvkey => $pvval) {
$ret[$pvkey] = array($pkey => $pvval);
}
}
}
echo '<pre>', print_r($ret), '</pre>';
In this case it prints out
Array
(
[6] => Array
(
[comment] => test comment
)
[5] => Array
(
[comment] => 111222
)
)
1
Unfortunally it print out only comment. I need to add other rows: queue,sum,sumAccD,sumAccC. Array must look like this:
Array
(
[6] => Array
(
[queue] => 5
[sum] => ''
....
[comment] => test comment
)
[5] => Array
(
[queue] => 2
[sum] => 2.1
....
[comment] => 111222
)
)
1
Please help merge them.
Thanks.
Look at this line:
$ret[$pvkey] = array($pkey => $pvval);
You're assigning the key to a new array every time, overwriting what was previously there.
In your case, 'comment' is the last key that is processed, so that's going to be the only key in the final array.
Instead of this, you could define a new array only once outside the inner for, like this:
$ret[$pvkey] = array();
And then assign your values to that array in the inner for loop as you would normally do (so no more creating arrays there!)
Problem solved by replacing
$ret[$pvkey] = array($pkey => $pvval);
with
$ret[$pvkey][$pkey] = $pvval;

Retrieve name-value pair into PHP array

I need some help. I have a variable containing this string;
[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]
I need to retrieve the id and value for each pair and make it any array in PHP.
You can use json_decode and pass the second param as true so it returns an array like this
$json = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$decoded = json_decode($json,true);
print_r($decoded);
Working Example
Output would be
Array
(
[0] => Array
(
[id] => 17
[value] => 123456789
)
[1] => Array
(
[id] => 18
[value] => 2012-06-13
)
[2] => Array
(
[id] => 19
[value] => Kampala
)
[3] => Array
(
[id] => 20
[value] => 1
)
.......
)
Which you can loop through using foreach like.
foreach($decoded as $de){
// access id with $de['id']
// access value with $de['value']
}
You have got an json string. You can convert it to an array by using function json_decode
Check this code .
$str = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"}, {"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$array = json_decode($str);
foreach($array as $temp){
echo "ID : ".$temp->id."\t Value: ".$temp->value;
echo "<br />";
}

Merge arrays together based on different values

I am having trouble thinking of the logic with the following problem:
I have the following array (has been snipped, as its much larger)
Array
(
[0] => Array
(
[code] => LAD001
[whqc] => GEN
[stocktag] => NONE
[qty] => 54
)
[1] => Array
(
[code] => LAD001
[whqc] => GEN
[stocktag] => NONE
[qty] => 6
)
[2] => Array
(
[code] => LAD004
[whqc] => HOLD
[stocktag] => NONE
[qty] => 6
)
)
I basically need to comebine all the keys in this array so that where the code, whqc and stocktag are the same, add the qty values together. With the example below, I need to end up with this:
Array
(
[0] => Array
(
[code] => LAD001
[whqc] => GEN
[stocktag] => NONE
[qty] => 60
)
[1] => Array
(
[code] => LAD004
[whqc] => HOLD
[stocktag] => NONE
[qty] => 6
)
)
As the first and second keys of the array had the same code, whqc and stocktag, the qty's have been added together into the one key.
Any ideas?
I would suggest combining the group values in to a hash, storing the full array under the hash as a key and if you have a duplicate, add the quantity, then do array_values() to pull the results.
$aggregated = array();
foreach ($records as $cRec) {
// The separator | has been used, if that appears in the tags, change it
$cKey = md5($cRec['code'] . '|' . $cRec['whqc'] . '|' . $cRec['stocktag']);
if (array_key_exists($cKey, $aggregated)) {
$aggregated[$cKey]['qty'] += $cRec['qty'];
} else {
$aggregated[$cKey] = $cRec;
}
}
// Reset the keys to numerics
$aggregated = array_values($aggregated);
I would try something like:
$output = array();
foreach($array as $details){
//make distinct key
$key = $details['code'].'_'.$details['whqc'];
if(!isset($output[$key])){
$output[$key] = $details;
}else{
$output[$key]['qty'] += $details['qty'];
$output[$key]['stocktag'] = $details['stocktag'];
}
}
$output = array_values($output);
print_r($output);
update: Orbling was first ;-)

Categories