I have an API which returns a response in form of an array. I want to extract the elements from this array and save them in my database. I have tried using the explode function but it seems I am missing something. Below is an exact sample response from the retrieve.
Array
(
[Response] => Array
(
[external_reference] => bablaba
[withdraw_request_id] => babalalal
[amount] => bababababa
[status] => ababababab
[message] => ababababa.
[new_balance] => babababa
[amount_sent] => ababababa
[currency_sent] => ababababa
[charge_amount] => ababababa
[charge_currency] => babababa
[currency] => abababaab
)
)
What's the point to duplicate the variables?
When you want to save the amount for exemple use $array['response']['amount']
You have an array Response inside the array $Array. In order to convert array element values into variables. You must navigate inside $Array and inside Response to do so you write : $bigArray['smallArray']['element'].
$external_reference = $Array['Response']['external_reference'];
$withdraw_request_id = $Array['Response']['withdraw_request_id'];
$amount = $Array['Response']['amount'];
$status = $Array['Response']['status'];
$message = $Array['Response']['message'];.
$new_balance = $Array['Response']['new_balance'];
$amount_sent = $Array['Response']['amount_sent'];
$currency_sent = $Array['Response']['currency_sent'];
$charge_amount = $Array['Response']['charge_amount'];
$charge_currency = $Array['Response']['charge_currency'];
$currency = $Array['Response']['currency'];
To learn more about multidimensional arrays read: this
Related
I store form elements as serialized data in a cookie.
On another page I want to collect this cookie but the cookie contains this string:
form_key=kcE3W2vzParNhPN5&options%5B1508%5D=2025&options%5B1509%5D=1234&options%5B1510%5D=5678&options%5B1511%5D=&options%5B1512%5D=&options%5B1513%5D=&productId=59891
%5B and %5D are brackets I figured, but how can I look through all these options in the string and get their ID + value into an array with PHP.
So from above string I would like to create an array with:
arr = array (
[1508] = '2025';
[1509] = '1234';
[1510] = '5678';
[1511] = '';
[1512] = '';
);
I think what you want is parse_str():
$str = "form_key=kcE3W2vzParNhPN5&options%5B1508%5D=2025&options%5B1509%5D=1234&options%5B1510%5D=5678&options%5B1511%5D=&options%5B1512%5D=&options%5B1513%5D=&productId=59891";
$output = array();
parse_str($str, $output);
print_r($output); // $output['options'] will contain your array you're looking for.
See execution here:
Array
(
[form_key] => kcE3W2vzParNhPN5
[options] => Array
(
[1508] => 2025
[1509] => 1234
[1510] => 5678
[1511] =>
[1512] =>
[1513] =>
)
[productId] => 59891
)
I am having trouble sorting through a multidimensional array that I am pulling from an XML feed that can be different every time. I need to find something and place the result in a variable. I am still learning PHP and this unfortunately is a bit over my head.
I'll break down what I have. An example of my array contained in $valsarray:
Array
( [0] => Array
(
[tag] => GIVENNAME
[type] => complete
[level] => 8
[value] => peter
)
[1] => Array
(
[tag] => FAMILYNAME
[type] => complete
[level] => 8
[value] => rabbit
)
[2] => Array
(
[tag] => COMPLETENUMBER
[type] => complete
[level] => 9
[value] => 123-345-4567
)
[3] => Array
(
[tag] => URIID
[type] => complete
[level] => 9
[value] => customerEmail#gmail.com
)
)
Now I understand that I can get the result by using: $phone = $valsarray[2][value];
However, my problem is that if no phone number was given, the XML feed will not contain the phone number array so Array 3 would become Array 2.
So my question is how would I go about looping through the arrays to find if COMPLETENUMBER exists and then assigning the phone number contained in value to a $phone variable?
Here's one way:
$tags = array_column($valsarray, null, 'tag');
if(isset($tags['COMPLETENUMBER'])) {
$phone = $tags['COMPLETENUMBER']['value'];
}
Or if you only care about value:
$tags = array_column($valsarray, 'value', 'tag');
if(isset($tags['COMPLETENUMBER'])) {
$phone = $tags['COMPLETENUMBER'];
}
So in short:
Get an array of the value values indexed by tag
If COMPLETENUMBER index is set then get the value from value
After the array_column() you can then get whatever value you want:
$email = $tags['URIID'];
This loop would do it:
foreach($valsarray as $fieldArray)
{
if ($fieldArray['tag'] === 'COMPLETENUMBER')
{
$phone = $fieldArray['value'];
break;
}
}
If you need to do this type of thing repeatedly on the same array, you'd be better off reindexing it than searching each time. You could reindex like this:
foreach($valsarray as $key => $fieldArray)
{
$valsarray[$fieldArray['tag']] = $fieldArray;
unset($valsarray[$key]);
}
After reindexing it, you can do this for any field you want:
$phone = $valsarray['COMPLETENUMBER']['value'];
You can array_filter to get only COMPLETENUMBER entries, and set $phone if one is found.
$items = array_filter($valsarray, function($x) { return $x['tag'] == 'COMPLETENUMBER'; });
$phone = $items ? reset($items)['value'] : null;
Based on your other comments, if you want to get the values for a subset of tags from the array, you can use in_array in the array_filter callback. This could be wrapped in the array_column suggested in AbraCadaver's answer to get an array of values for any of the tags you're interested in:
$tags = ['COMPLETENUMBER', 'URIID'];
$data = array_column(array_filter($valsarray, function($x) use ($tags) {
return in_array($x['tag'], $tags);
}), 'value', 'tag');
The result would be like:
array (size=2)
'COMPLETENUMBER' => string '123-345-4567' (length=12)
'URIID' => string 'customerEmail#gmail.com' (length=23)
The following is a profile array printed using r_print:
Array
(
[0] => Array
(
[Title] => Profile
[Name] => Veritas
[NKey] => Key_1
[SKey] => Key_2
)
[1] => Array
(
[Title] => Access
[Admin] => True
[Banned] => False
[Public] => True
)
)
What I'm trying to do, is simply retrieve elements of that array.
IE,
$profile[] = ...; //GET_ARRAY
$user = $profile[0]['Name'];
$key_1 = $profile[0]['NKey'];
$key_2 = $profile[0]['SKey'];
$admin = $profile[1]['Admin'];
For some reason, the above code doesn't work, though logically it should work without a problem.
What IS returned, is just the character 'A' if I target anything within the array.
You are adding another level to your array by assigning the array to $profile[]. The brackets turn $profile into an array and then adds that array to it causing the extra level.
$profile[] = ...; //GET_ARRAY
should just be
$profile = ...; //GET_ARRAY
Figured out what I was looking for, thought PHP automatically formated arrays (string data) passed from another page. I solved my issue using serialize() & unserialize().
I call an webservice using PHP 5.3.1 and my request looks as so:
<?php
$client = new SoapClient('the API wsdl');
$param = array(
'LicenseKey' => 'a guid'
);
$result = $client->GetUnreadIncomingMessages($param);
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Here is the response that I get back:
stdClass Object
(
[GetUnreadIncomingMessagesResult] => stdClass Object
(
[SMSIncomingMessage] => Array
(
[0] => stdClass Object
(
[FromPhoneNumber] => the number
[IncomingMessageID] => message ID
[MatchedMessageID] =>
[Message] => Hello there
[ResponseReceiveDate] => 2012-09-20T20:42:14.38
[ToPhoneNumber] => another number
)
[1] => stdClass Object
(
[FromPhoneNumber] => the number
[IncomingMessageID] =>
[MatchedMessageID] =>
[Message] => hello again
[ResponseReceiveDate] => 2012-09-20T20:42:20.69
[ToPhoneNumber] => another number
)
)
)
)
To get to the data you want to retrieve you need to navigate through multiple nested objects. The objects are of stdClass type. It is my understanding that you can access nested objects in a stdClass but I am going to cast them to arrays to make indexing easier.
So start with:
<?php
$client = new SoapClient('the API wsdl');
$param = array('LicenseKey' => 'a guid');
$result = $client->GetUnreadIncomingMessages($param);
You now have a $result vavialble of type stdClass. This has a single object in it also of type stdClass called "GetUnreadIncomingMessagesResult." This Object in turn contains an array called "SMSIncomingMessage." That array contains a varriable number of objects of stdClass that hold the data you want.
So we do the following:
$outterArray = ((array)$result);
$innerArray = ((array)$outterArray['GetUnreadIncomingMessagesResult']);
$dataArray = ((array)$innerArray['SMSIncomingMessage']);
Now we have an array holding each object we want to extract data from. So we loop through this array to get the holding object, cast the holding object to an array and than extract the necessary information. You do this as follows:
foreach($dataArray as $holdingObject)
{
$holdingArray = ((array)$holdingObject);
$phoneNum = $holdingArray['FromPhoneNumber'];
$message = $holdingArray['Message'];
echo"<div>$fphone</div>
<div>$message</div>";
}
?>
This should give you the output you are looking for. You can adjust where you index the holdingArray to get out whatever specific information you are looking for.
The complete code looks like:
<?php
$client = new SoapClient('the API wsdl');
$param = array('LicenseKey' => 'a guid');
$result = $client->GetUnreadIncomingMessages($param);
$outterArray = ((array)$result);
$innerArray = ((array)$outterArray['GetUnreadIncomingMessagesResult']);
$dataArray = ((array)$innerArray['SMSIncomingMessage']);
foreach($dataArray as $holdingObject)
{
$holdingArray = ((array)$holdingObject);
$phoneNum = $holdingArray['FromPhoneNumber'];
$message = $holdingArray['Message'];
echo"<div>$fphone</div>
<div>$message</div>";
}
?>
I'm taking some json, made by OpenLibrary.org, and remake a new array from the info.
Link to the OpenLibrary json
here is my PHP code to decode the json:
$barcode = "9781599953540";
function parseInfo($barcode) {
$url = "http://openlibrary.org/api/books?bibkeys=ISBN:" . $barcode . "&jscmd=data&format=json";
$contents = file_get_contents($url);
$json = json_decode($contents, true);
return $json;
}
the new array I'm trying to make looks something like this:
$newJsonArray = array($barcode, $isbn13, $isbn10, $openLibrary, $title, $subTitle, $publishData, $pagination, $author0, $author1, $author2, $author3, $imageLarge, $imageMedium, $imageSmall);
but when I try to get the ISBN_13 to save it to $isbn13, I get an error:
Notice: Undefined offset: 0 in ... on line 38
// Line 38
$isbn13 = $array[0]['identifiers']['isbn_13'];
And even if I try $array[1] ,[2], [3].... I get the same thing. What am I doning wrong here! O I know my Valuable names might not be the same, that's because they are in different functions.
Thanks for your help.
Your array is not indexed by integers, it is indexed by ISBN numbers:
Array
(
// This is the first level of array key!
[ISBN:9781599953540] => Array
(
[publishers] => Array
(
[0] => Array
(
[name] => Center Street
)
)
[pagination] => 376 p.
[subtitle] => the books of mortals
[title] => Forbidden
[url] => http://openlibrary.org/books/OL24997280M/Forbidden
[identifiers] => Array
(
[isbn_13] => Array
(
[0] => 9781599953540
)
[openlibrary] => Array
(
[0] => OL24997280M
)
So, you need to call it by the first ISBN, and the key isbn_13 is itself an array which you must access by element:
// Gets the first isbn_13 for this item:
$isbn13 = $array['ISBN:9781599953540']['identifiers']['isbn_13'][0];
Or if you need a loop over many of them:
foreach ($array as $isbn => $values) {
$current_isbn13 = $values['identifiers']['isbn_13'][0];
}
If you expect only one each time and must be able to get its key without knowing it ahead of time but don't want a loop, you can use array_keys():
// Get all ISBN keys:
$isbn_keys = array_keys($array);
// Pull the first one:
$your_item = $isbn_keys[0];
// And use it as your index to $array
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];
If you have PHP 5.4, you can skip a step via array dereferencing!:
// PHP >= 5.4 only
$your_item = array_keys($array)[0];
$isbn13 = $array[$your_item]['identifiers']['isbn_13'][0];