How to reformat this array without knowing the keys in advance - php

I'm querying an API and getting a response back with various countries. Here is the relevant array I'm working with and what it prints out.
print_r($apiResponse['response']['data'][0]['countries']);
prints this:
Array ( [US] => Array ( [id] => 840 [code] => US [name] => United States [regions] => Array ( ) ) [CA] => Array ( [id] => 124 [code] => CA [name] => Canada [regions] => Array ( ) ) )
I am looking to save an array of only the two character country codes from that data. The only thing is the key is unknown to me when I query it so I don't know how to access the [code] section of it to save it to my new array.
I want to end up being able to take whatever amount of countries the API sends back and save the two character codes in a format like this:
'country_codes' => array('US','CA','UK','AU')
Thanks for your help!

Use the array_keys() function. Here you have the documentation.

Related

PHP search/filter array with given conditions, recursively

I am getting data from an api (that I cannot query agains, just get lump of data), and then I need to query against those data like I would do using database. Only It would be great if I could do it recursively.
Data example
[0] => Array
(
[id] => 1
[url] => https://domain.com/api/1.0/item/1/
[name] => some_item
[category] => some category
[created_by] => Array
(
[id] => 1
[screen_name] => tomino
)
[current_user_domain_access] => Array
(
[is_active] => 1
[is_administrator] => 1
)
[alerts_enabled] => 0
)
(much shortened version)
I receive an array of objects like that and then I need to select/filter/search by values.
Something like this
SomeModel::find(['category'=>'some category','current_user_domain_access' => ['is_administrator' => 1]]);
Is that something that would be possible in PHP? I was thinking about flattening the array, but then there might be key conflicts
1) select data : You can select data by (array_name->id),(array_name->url) and so on...
2)Filter : add conditions according to requirement
3)search : in_array(),array_search

How can I access ID array of its value

I am analyzing someone's else code where I found during debugging the type and values of a class variable during run time:
echo print_r($this->_out);
Array
(
[id] => -1
[fieldErrors] => Array
(
)
[error] =>
[data] => Array
(
)
[row] => Array
(
[DT_RowId] => row_177
[id] => 177
[last_name] => sdfdsf
[first_name] => dsf
[homeaddr] => sdfdsfsdfdsfdsfdsfdsf
[email] => s#jj.com
[officeaddr] => wwwwwwwwwwwwwwwwwwwwwwww
[mobile] => 11111111
[age] => 11
[chargeamt] => 11
[start_date] => 11/11/2011
)
)
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am a newbie in PHP and would like to know how I can access [id] => 177 value i.e. value 177.
I tried out many ways
$this->_out['row']['id'][0]
It gave me below result:
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
while
I tried out many ways
$this->_out['row']['id']
It gave me below result:
177{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
and others but its just not giving me the expected.
How can I access the value as desired?
You are doing it right. $this->_out['row']['id'] will return desired result (check why you get also JSON string that is not part of print_t($this->_out).
This will return result 177:
$this->_out['row']['id'];
And since in PHP you can access string characters as array, this will returns first character in string (that is 1):
$this->_out['row']['id'][0];
And this will throw error as there is no such index (string length is 3, so last index is 2):
$this->_out['row']['id'][5];
The print_r result is an array with more arrays on it. So first of all you must find the index of the main array which index represents the sub-array with the value you are looking for. And then you must use this index to access the sub array values.

SugarCRM REST API, how to get Contacts related to an Account

I am using SugarCRM Pro 6.5.5. I am trying to do some integration into another application, so I need to do some API calls from that other application. I am using the REST API v2. At this point, I need to get a Contact that is related to an Account via the account ID. I have tried both get_relationships() and get_entry_list(), but I can't get either of them to work.
Here's my input for get_relationships():
{"session":"eujfbfsfjgni98m0mivl6jm6r2","module_name":"Accounts","module_id":"c03d0649-0525-2f90-1206-50881e87d7dd","link_field_name":"contacts"}
I have tried many variations of this, and several other options, but nothing did what I wanted. This is the output from above:
stdClass Object
(
[entry_list] => Array
(
[0] => stdClass Object
(
[id] =>
[module_name] => Contacts
[name_value_list] => stdClass Object
(
[deleted] => stdClass Object
(
[name] => deleted
[value] => 0
)
[do_not_call] => stdClass Object
(
[name] => do_not_call
[value] => 0
)
)
)
)
[relationship_list] => Array
(
)
)
I don't see how this information could ever be useful.
Next up, I tried get_entry_list() with a query to select only the Contacts that had the given account ID. Here's my input for that:
{"session":"8mol33e7kdq6girugu30dnt074","module_name":"Contacts","query":"accounts.id = 'c03d0649-0525-2f90-1206-50881e87d7dd'"}
I am using accounts.id because I have read in similar questions, that is correct. I've tried many other things, like: contacts.account_id, account_id, etc. In every case, I get a MySQL error in the log stating the column is invalid.
SugarCRM: how to get all contacts for an account via REST API
This question is relevant, and seems to be the exact same problem. I tried adding a link_name_to_fields_array option to my input, but no matter what value I provide, it results in the following MySQL error in the log:
AND jt11.deleted=0 where (Array) AND contacts.deleted=0: MySQL error 1054: Unknown column 'Array' in 'where clause'
Dafuq?
Thanks.
Thanks to ychaouche, I figured it out.
I was able to use the get_relationships() method after all. I had tried before adding the related_fields to my input, but all that did was result in an empty result set. The answer? Set related_module_query to an empty string... and now the result set is not empty. Yep, my 3+ hours of furious Googleing last night is because of that.
So, here is some working code in case anyone else has this problem:
{
"session": "iov9pg9kvvl60librung1h5fh6",
"module_name": "Accounts",
"module_id": "c03d0649-0525-2f90-1206-50881e87d7dd",
"link_field_name": "contacts",
"related_module_query": "",
"related_fields": [
"first_name",
"last_name"
],
"deleted": false
}
This got me the following result set:
stdClass Object
(
[entry_list] => Array
(
[0] => stdClass Object
(
[id] =>
[module_name] => Contacts
[name_value_list] => stdClass Object
(
[first_name] => stdClass Object
(
[name] => first_name
[value] => John
)
[last_name] => stdClass Object
(
[name] => last_name
[value] => Smith
)
)
)
)
[relationship_list] => Array
(
)
)
You can of course specify different fields in related_fields and get different pieces of data.
Take a look at sugarcrm/tests/service/RESTAPI4Test.php. It's got plenty of examples on how to use the REST API. It's a common practice to look at test code for code examples on how to use a library/framework/API. Tests are in this sense a very good documentation.
Hope that helps.

Grouping php array items based on user and created time

This is an array of objects showing a user uploading photos:
Array
(
[12] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:36:41
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photo] => stdClass Object
(
[id] => 4181
)
)
[44] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:37:15
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photo] => stdClass Object
(
[id] => 4180
)
)
)
However instead of showing:
mr smith uploaded one photo
mr smith uploaded one photo
I'd like to display:
mr smith uploaded two photos
by grouping similar items, grouping by user ID and them having added them within, let's say 15 minutes of each other. So I'd like to get the array in this sort of shape:
Array
(
[12] => stdClass Object
(
[type] => photo
[created] => 2010-05-14 23:36:41
[user] => stdClass Object
(
[id] => 760
[username] => mrsmith
)
[photos] => Array
(
[0] => stdClass Object
(
[id] => 4181
)
[1] => stdClass Object
(
[id] => 4180
)
)
)
)
preserving the first item of the group and it's created time, and supplementing it with any other groupable photos and then unsetting any items that were grouped (so the final array doesn't have key 44 anymore as it was grouped in with 12).
The array contains other actions than just photos, hence the original keys of 12 and 44. I just can't figure out a way to do this efficiently. I used to use MySQL and PHP to do this but am trying to just use pure PHP for caching reasons.
Can anyone shed any insights? I thought about going through each item and seeing if I can group it with the previous one in the array but the previous one might not necessarily be relevant or even a photo. I've got total brain freeze :(
If the entries are ordered by date you can do the following:
Keep an array (let's call it $foo) with all the photos in a 15 minute window. Use the array as a FIFO list (use array_shift to remove items and $foo[] = ... to add).
Iterate over the original array
Check the date of the current item and remove from the beginning of $foo all the entries whose date is more than 15 minutes less than the current item. Once you find an item that for something that happened less than 15 minutes ago, you can stop (it's a one line for loop).
Iterate over the the entries in $foo
If a photo by the same person is found, then
Alter the reference stored in $foo so that the new data is added
Remove the current item from the original array
break from inner loop
If not
Add a reference to the current item to the end $foo with $foo = &$var.
You may then reindex the original array with array_values to fill the gaps.

foreach loops & stdclass objects

I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );

Categories