I have a Json Script with an Array inside and Array which looks like this shortened:
Array
(
[assets] => Array
(
[CGGD.AS] => Array
(
[shortName] => iShares Global Govt Bond Climat
[sector] =>
[industry] =>
[country] =>
[longBusinessSummary] =>
[currency] => USD
[marketCap] =>
[logo_url] =>
[Anlageklasse] => Anleihen
[Anmerkungen] => Staatsanleihen Welt
[Nachhaltigkeit] => 1
[Ist_Alternative] => 1
[weights] => 0.86563025602977
)
[SUOE.MI] => Array
(
[shortName] => ISHARES EUR CORP BOND SRI UCITS
[sector] =>
[industry] =>
[country] =>
[longBusinessSummary] =>
[currency] => EUR
[marketCap] =>
[logo_url] =>
[Anlageklasse] => Anleihen
[Anmerkungen] => Unternehmensnaleihen EUR
[Nachhaltigkeit] => 1
[Ist_Alternative] => 1
[weights] => -0.47997445382071
)
)
[risk] => 0.05323390949106
[return] => 1.1125842376311
)
Now I want to work with the single variables shortName, industry, etc.
When I tried to call the function with
print_r($json_data['assets']['CGGD.AS']['shortName']);
it worked perfectly fine. When I use
print_r($_POST['assets'][0][0]);
it is not working at all and gives me the following warning:
Warning: Undefined array key "assets" in
C:\xampp\htdocs\test\ergebnisdarstellung.php on line 52
Warning: Trying to access array offset on value of type null in
C:\xampp\htdocs\test\ergebnisdarstellung.php on line 52
The problem I have is that I will not know what name will be in the second brackets like CGGD.AS and because of this I can not use the working function. I will not now how long the array is either and numbers are not working. Because of this I do not know how to call the single variabless without using the name.
How can I call the function?
To get all shortName you can loop your array:
foreach ($json_data['assets'] as $key => $data) {
print_r($data['shortName']);
}
If you want just shortName of first element, then use current:
$item = current($json_data['assets']);
print_r($item['shortName']);
$arr = [
'assets' => [
'CGGD.AS' => [
'shortName' => 'iShares Global Govt Bond Climat',
// other fields omitted
],
'SUOE.MI' => [
'shortName' => 'ISHARES EUR CORP BOND SRI UCITS',
// other fields omitted
]
],
'risk' => 0.05323390949106,
'return' => 1.1125842376311
];
$assetsKeys = array_keys($arr['assets']);
$shortNames = array_column($arr['assets'], 'shortName');
$result = array_combine($assetsKeys, $shortNames);
print_r($result);
// This will print:
// Array
// (
// [CGGD.AS] => iShares Global Govt Bond Climat
// [SUOE.MI] => ISHARES EUR CORP BOND SRI UCITS
// )
Related
I'm pulling results from an XML SOAP service which returns results in structure that doesn't work too well with encoding the result to json then decoding into an array.
Here's an example of the output I've rendered by running the following function on my results:
$result[implode('/',$keys)] = $val;
Array
(
[accountList/accountNo] => 0610010000048744
[accountList/accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountList/accountStatus] => DORMANT
[accountList/arrearAmount] => 80000.0
[accountList/arrearDays] => 30
[accountList/balanceAmount] => 120000.0
[accountList/disputed] => false
[accountList/isMyAccount] => false
[accountList/lastPaymentDate] => 2015-01-23T00:00:00+03:00
[accountList/listingDate] => 2014-09-30T00:00:00+03:00
[accountList/pastDueDate] => 1900-01-01T00:00:00+03:00
[accountList/principalAmount] => 300000.0
[accountList/scheduledPaymentAmount] => 0.0
[accountList/tradeSector] => Bank Sector Bureau
[accountList/worstArrear] => 30
[accountList/currency] => KES
[personalProfile/crn] => 79908
[personalProfile/dateOfBirth] => 1959-01-01T00:00:00+02:45
[personalProfile/fullName] => Surname 79908 OtherNames 79908
[personalProfile/gender] => F
[personalProfile/nationalID] => ID79908
[summary/npaAccounts/mySector] => 2
[summary/npaAccounts/otherSectors] => 0
[summary/npaTotalValueList/currency] => KES
[summary/npaTotalValueList/mySector] => 120000.0
[summary/npaTotalValueList/otherSectors] => 0.0
[summary/openAccounts/mySector] => 2
[summary/openAccounts/otherSectors] => 0
)
Because the results and keys always vary depending on request I make to the server, I'd like to build a multidimensional array through a recursive function, in some instances the keys eg. accountList may have multiple values
An expected result would look something like this:
Array
(
[accountList] => Array
(
[accountNo] => 0610010000048744
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => DORMANT
[arrearAmount] => 80000.0
[arrearDays] => 30
[balanceAmount] => 120000.0
[disputed] => false
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
Array
(
[accountNo] => 0610010000048788
[accountOpeningDate] => 2014-09-01T00:00:00+03:00
[accountStatus] => ACTIVE
[arrearAmount] => 10000.0
[arrearDays] => 90
[balanceAmount] => 10000.0
[disputed] => TRUE
[isMyAccount] => false
[lastPaymentDate] => 2015-01-23T00:00:00+03:00
[listingDate] => 2014-09-30T00:00:00+03:00
[pastDueDate] => 1900-01-01T00:00:00+03:00
[principalAmount] => 300000.0
[scheduledPaymentAmount] => 0.0
[tradeSector] => Bank, Sector Bureau
[worstArrear] => 30
[currency] => KES
)
[personalProfile] => Array
(
[crn] => 79908
[dateOfBirth] => 1959-01-01T00:00:00+02:45
[fullName] => Surname, 79908 OtherNames 79908
[gender] => F
[nationalID] => ID79908
)
)
I think you are trying to achieve this thing.
Try this code snippet here
explode("/", $key) this will return array which will contain two values.
list($first,$second)=explode("/", $key); and through this i am putting those values, one in $first and other in $second.
<?php
ini_set('display_errors', 1);
$data=Array
(
"accountList/accountNo"=>"0610010000048744",
"accountList/accountOpeningDate"=>"2014-09-01T00:00:00+03:00",
"accountList/accountStatus"=>"DORMANT",
"accountList/arrearAmount"=>"80000.0",
"accountList/arrearDays"=>"30",
"accountList/balanceAmount"=>"120000.0",
"accountList/disputed"=>"false",
"accountList/isMyAccount"=>"false",
"accountList/lastPaymentDate"=>"2015-01-23T00:00:00+03:00",
"accountList/listingDate"=>"2014-09-30T00:00:00+03:00",
"accountList/pastDueDate"=>"1900-01-01T00:00:00+03:00",
"accountList/principalAmount"=>"300000.0",
"accountList/scheduledPaymentAmount"=>"0.0",
"accountList/tradeSector"=>"Bank, Sector Bureau",
"accountList/worstArrear"=>"30",
"accountList/currency"=>"KES",
"personalProfile/crn"=>"79908",
"personalProfile/dateOfBirth"=>"1959-01-01T00:00:00+02:45",
"personalProfile/fullName"=>"Surname, 79908 OtherNames 79908",
"personalProfile/gender"=>"F",
"personalProfile/nationalID"=>"ID79908",
"sample/data/data1"=>"ID79908",//added a sample data
);
$result=array();
foreach($data as $key => $value)
{
$string="";
$numberOfWords=explode("/", $key);
foreach($numberOfWords as $newValue)
{
$string.="['$newValue']";
}
eval('$result'.$string."= \"$value\";");
}
print_r($result);
The way you want to build your array is as follows. The reason is that you want things like "accountList" and "personalProfile" to be unique keys within the array, much like they would be in a relational database.
$array = $array('accountList'=>array("accountNo"=>"0610010000048744",
"accountOpenDate"=>"2014-09-
01T00:00:00+03:00"),array("personalProfile"=>array("...and so on."));
I have an array and I'm willing to find a value of a specific key in case another key's value is X.
My array has several other arrays with the following structure:
[3] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
)
I'm willing to find in the main array, all the values of SREDNJI KURS only if the value of OZNAKA VALUTE is "CNY".
As far as I understood from your question:
var_dump($data);
/*
[0] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
),
[1] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
)*/
Just use a simple loop over the array and check where the value of that specific key is CNY.
foreach($data as $row){
if($row['OZNAKA VALUTE'] == "CNY"){
echo $row['SREDNJI KURS'];
//or save it in an array or whatever you'd like to do with it.
}
}
I am trying to create an array out of looped data. The variables contain looped data. All works fine, but when array is outputted, the index gets stuck at 0 and doesn't move up from 0 to 1 etc. I wonder what the problem is and how I can get this fixed.
Thanks.
$productinfo = array(
array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" )
);
$productinfojson= json_encode($productinfo);
$output = json_decode($productinfojson, TRUE);
echo "<pre>";
print_r( $output );
echo "</pre>";
The above outputs:
Array
(
[0] => Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
)
Array
(
[0] => Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
)
UPDATE if only one array is used.
code:
$productinfo = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" );
OUTPUT
Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
The issue stems straight from your array creation. There doesn't seem to be a loop anywhere in your code either....
Anyways, lets sort out your array creation. I assume you're getting the data from a database/data source and assigning it to variables, inputting it into an array? Well the way you currently have it, it's overwriting the first index element in the array.
Disclaimer: The below is pseudo code, until you update with your actual loop code..
$productinfo = array();
while($row = FETCH_DATA_FROM_SQL()) {
// assign it to variables here...?
$productinfo[] = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link"
);
}
That will add each element to the new $productinfo array and you should be able to loop through the elements correctly.
One more thing to note, you're decoding your json like this:
$output = json_decode($productinfojson, TRUE);
That second parameter (TRUE), turns it into an associative array, not an object. So when you loop it as an object like below:
foreach($response->products->product as $product) {...
It isn't going to work. If you want it as an object, remove the second parameter (TRUE), otherwise loop it as an array:
foreach($response['products']['product'] as $product) {...
I have this 3 and 4 multidimensionnal array ($response) which I need to "extract" some values.
Array (
[status] => 200
[response] => Array (
[api_id] => 38229dd9-8c52-11e5-80f6-22000afd0039
[meta] => Array (
[limit] => 20
[next] => /v1/Account/xxx/Call/?limit=20&offset=20
[offset] => 0
[previous] =>
[total_count] => 57 )
[objects] => Array (
[0] => Array (
[answer_time] => 2015-11-13 18:36:19+01:00
[bill_duration] => 10
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 10
[call_uuid] => dcd94e59-8775-4c81-a4b1-cd5d41d630c6
[end_time] => 2015-11-13 18:36:29+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 18:36:18+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/dcd94e59-8775-4c81-a4b1-cd5d41d630c6/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
[1] => Array (
[answer_time] => 2015-11-13 15:52:01+01:00 [
bill_duration] => 48
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 48
[call_uuid] => b2d3de5d-a047-4409-9f7a-825373c38f0a
[end_time] => 2015-11-13 15:52:48+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 15:52:00+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/b2d3de5d-a047-4409-9f7a-825373c38f0a/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
...
In the [meta] array, I need the [total_count] value and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
I have tried foreach within foreach or access datas with $response[0][0][0] but nothing do.
If someone could lead me to the solution...
Thanks a lot !!
You can access the meta array through $response['response']['meta']. As you can see from your array, both response and meta are keys, and so is total_count. Hence, accessing total count is done by $response['response']['meta']['total_count'].
To then loop through all your objects, simply do
foreach ($response['response']['objects'] as $object) {
print_r($object);
}
You can also access every attribute of the object individually by using the array keys:
foreach ($response['response']['objects'] as $object) {
echo $object['answer_time'];
echo $object['bill_duration'];
echo $object['billed_duration'];
echo $object['call_direction'];
echo $object['call_duration'];
echo $object['call_uuid'];
echo $object['end_time'];
echo $object['from_number'];
echo $object['initiation_time'];
echo $object['parent_call_uuid'];
echo $object['resource_uri'];
echo $object['to_number'];
echo $object['total_amount'];
echo $object['total_rate'];
}
First, to verify, if $array is the name of your array:
$response = $array["response"];
In the [meta] array, I need the [total_count] value
echo $response["meta"]["total_count"];
and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
Use a foreach() function for all the objects:
foreach($response["objects"] as $object){
print_r($object);
}
You can use the "count" function with "COUNT_RECURSIVE" flag. It counts all the items inside the 'mixed' var. It counts parent element too.
count($array['objects'],COUNT_RECURSIVE);
example
$cibo = array(
'frutta' => array('arancia', 'banana', 'mela'),
'verdura' => array('carota', 'zucchina', 'piselli')
);
echo count($cibo,COUNT_RECURSIVE); // output 8
I'm sending a string of data via CURL using data from post, and receiving a response in a string as well which is in the form on an array. I'm trying to convert such response into an actual Array. Heres the code I have so far:
the response string im getting is this:
Test transaction_id="2401_02-29-12_22:28:34_0" action="payment"
result="success" to_from="to" amount="205.00" gross="205.00"
net="-0.85" custom="" business="XXXX#XXXX.com" item_name="XXXXX.XXX"
item_code="Product Name 3," quantity="1" transaction_type="authorized
payment" transaction_status="pending" transaction_date="2012-02-29
22:28:34" processing_rate="0.85" discount_fee="0.00"
first_name="TESTNAME" last_name="TESTLNAME" address="TESTADDRESS"
city="TESTCITY" state_or_province="AL" country="US"
zip_or_postal_code="12345" phone="1234562002" email="email#wemail.es"
shipment="yes" shipping_address="TESTADDRESS" shipping_city="TESTCITY"
shipping_state_or_province="AL" shipping_country="US"
shipping_zip_or_postal_code="12345" processing_time="0.2187"
And the code im using to get such response is
<?php
// Get variables from POST array into a string
$post_str = "action=payment&business=" .urlencode($this->input->post('business'))
."&vericode=" .urlencode($this->input->post('vericode'))
."&item_name=" .urlencode($this->input->post('item_name'))
."&item_code=" .urlencode($this->input->post('item_code'))
."&quantity=" .urlencode($this->input->post('quantity'))
."&amount=" .urlencode($this->input->post('amount'))
."&cc_type=" .urlencode($this->input->post('cc_type'))
."&cc_number=" .urlencode($this->input->post('cc_number'))
."&cc_expdate=" .urlencode($this->input->post('cc_expdate_year')).urlencode($this->input->post('cc_expdate_month'))
."&cc_security_code=" .urlencode($this->input->post('cc_security_code'))
."&shipment=" .urlencode($this->input->post('shipment'))
."&first_name=" .urlencode($this->input->post('first_name'))
."&last_name=" .urlencode($this->input->post('last_name'))
."&address=" .urlencode($this->input->post('address'))
."&city=" .urlencode($this->input->post('city'))
."&state_or_province=" .urlencode($this->input->post('state_or_province'))
."&zip_or_postal_code=" .urlencode($this->input->post('zip_or_postal_code'))
."&country=" .urlencode($this->input->post('country'))
."&shipping_address=" .urlencode($this->input->post('shipping_address'))
."&shipping_city=" .urlencode($this->input->post('shipping_city'))
."&shipping_state_or_province=" .urlencode($this->input->post('shipping_state_or_province'))
."&shipping_zip_or_postal_code=".urlencode($this->input->post('shipping_zip_or_postal_code'))
."&shipping_country=" .urlencode($this->input->post('shipping_country'))
."&phone=" .urlencode($this->input->post('phone'))
."&email=" .urlencode($this->input->post('email'))
."&ip_address=" .urlencode($this->input->post('ip_address'))
."&website_unique_id=" .urlencode($this->input->post('website_unique_id'));
// Send URL string via CURL
$backendUrl = "https://www.veripayment.com/integration/index.php";
$this->curl->create($backendUrl);
$this->curl->post($post_str);
// get response from API
$return_str = $this->curl->execute();
?>
If the response you're receiving has elements separated by a space you might use
function parse($response)
{
$result = array();
$resparray = explode(' ', $response);
if ($resparray)
{
foreach ($resparray as $resp) {
$keyvalue = explode('=', $resp);
$result[$keyvalue[0]] = str_replace('"', '', $keyvalue[1]);
}
}
return $result;
}
Edited and corrected, Here's the output
Array ( [transaction_id] => 2401_02-29-12_22:28:34_0 [action] => payment [result] => success [to_from] => to [amount] => 205.00 [gross] => 205.00 [net] => -0.85 [custom] => [business] => XXXX#XXXX.com [item_name] => XXXXX.XXX [item_code] => Product [Name] => [3,"] => [quantity] => 1 [transaction_type] => authorized [payment"] => [transaction_status] => pending [transaction_date] => 2012-02-29 [22:28:34"] => [processing_rate] => 0.85 [discount_fee] => 0.00 [first_name] => TESTNAME [last_name] => TESTLNAME [address] => TESTADDRESS [city] => TESTCITY [state_or_province] => AL [country] => US [zip_or_postal_code] => 12345 [phone] => 1234562002 [email] => email#wemail.es [shipment] => yes [shipping_address] => TESTADDRESS [shipping_city] => TESTCITY [shipping_state_or_province] => AL [shipping_country] => US [shipping_zip_or_postal_code] => 12345 [processing_time] => 0.2187