for each loop PHP Facebook - php

I try to make a web application for my thesis.
Actually it is almost finished but I still have to find a way to store the likes of users in a database. I collect user information and try to see if there is a relation between movies that he or she like and user data elements that are saved in different SNSs. For single information it already save the things the way it should be. The problem is, that facebook work with arrays and objects and I am not able to find a way to save all the likes in a single string (and then save it in a database).
// Insert or update user data to the database
$fbUserData = array(
'oauth_provider' => 'facebook',
//basic profile
'oauth_uid' => $fbUserProfile['id'],
'first_name' => $fbUserProfile['first_name'],
'last_name' => $fbUserProfile['last_name'],
'picture' => $fbUserProfile['picture']['url'],
'email' => $fbUserProfile['email'],
'link' => $fbUserProfile['link'],
'age_range' => $fbUserProfile['age_range']['min'],
'currency' => $fbUserProfile['currency']['user_currency'],
'devices' => $fbUserProfile['devices'],//['hardware']
'gender' => $fbUserProfile['gender'],
'install_type' => $fbUserProfile['install_type'],
'installed' => $fbUserProfile['installed'],
'is_shared_login' => $fbUserProfile['is_shared_login'],
'is_verified' => $fbUserProfile['is_verified'],
'locale' => $fbUserProfile['locale'],
'name_format' => $fbUserProfile['name_format'],
'payment_pricepoints' => $fbUserProfile['payment_pricepoints'], //credits?
'security_settings' => $fbUserProfile['security_settings']['secure_browsing']['enabled'],
'test_group' => $fbUserProfile['test_group'],
'timezone' => $fbUserProfile['timezone'],
'updated_time' => $fbUserProfile['updated_time'],
'verified' => $fbUserProfile['verified'],
'video_upload_limits' => $fbUserProfile['video_upload_limits']['size'],
'viewer_can_send_gift' => $fbUserProfile['viewer_can_send_gift'],
//extended permissions
'relationship_status' => $fbUserProfile['relationship_status'],
'hometown' => $fbUserProfile['hometown']['name'],
'languages' => $fbUserProfile['languages'][0]['name'].",".$fbUserProfile['languages'][1]['name'].",".$fbUserProfile['languages'][2]['name'].",".$fbUserProfile['languages'][3]['name'].",".$fbUserProfile['languages'][4]['name'],
//'likes' => $fbUserProfile['likes'][0]['name'].",".$fbUserProfile['likes'][1]['name']
'favorite_athletes' => $fbUserProfile['favorite_athletes'][0]['name'].",".$fbUserProfile['favorite_athletes'][1]['name'].",".$fbUserProfile['favorite_athletes'][2]['name'].",".$fbUserProfile['favorite_athletes'][3]['name'].",".$fbUserProfile['favorite_athletes'][4]['name'].",".$fbUserProfile['favorite_athletes'][5]['name'].",".$fbUserProfile['favorite_athletes'][6]['name'],
);
$userData = $user->checkUser($fbUserData);
//print
echo $userData['languages'];
echo $userData['favorite_athletes'];
As you can see for languages, likes, favorite_athletes I coded it in the ugly way now to read the profile and store it. The problem is that some people have over 100 likes, and it is of course not handy to code it in this way. When I use the
for each it always bug...

If you're just interested in concatenating arrays for a single table then use PHPs implode function http://php.net/manual/en/function.implode.php
combined with an array map as mentioned here
How to use implode on an array of stdClass objects?
alternatively normalise your database as mentioned in a comment
'favorite_athletes' => implode(",", array_map(function($x) { return $x['name'];},$fbUserProfile['favorite_athletes']));
'likes' => implode(",", array_map(function($x){ return $x['name']}, $fbUserProfile['likes']['data']));

// Insert or update user data to the database
$fbUserData = array(
'oauth_provider' => 'facebook',
//basic profile
'oauth_uid' => $fbUserProfile['id'],
'first_name' => $fbUserProfile['first_name'],
'last_name' => $fbUserProfile['last_name'],
'picture' => $fbUserProfile['picture']['url'],
'email' => $fbUserProfile['email'],
'link' => $fbUserProfile['link'],
'age_range' => $fbUserProfile['age_range']['min'],
'currency' => $fbUserProfile['currency']['user_currency'],
'devices' => $fbUserProfile['devices'][0]['hardware'],
'gender' => $fbUserProfile['gender'],
'install_type' => $fbUserProfile['install_type'],
'installed' => $fbUserProfile['installed'],
'is_shared_login' => $fbUserProfile['is_shared_login'],
'is_verified' => $fbUserProfile['is_verified'],
'locale' => $fbUserProfile['locale'],
'name_format' => $fbUserProfile['name_format'],
'payment_pricepoints' => $fbUserProfile['payment_pricepoints'], //credits?
'security_settings' => $fbUserProfile['security_settings']['secure_browsing']['enabled'],
'test_group' => $fbUserProfile['test_group'],
'timezone' => $fbUserProfile['timezone'],
'updated_time' => $fbUserProfile['updated_time'],
'verified' => $fbUserProfile['verified'],
'video_upload_limits' => $fbUserProfile['video_upload_limits']['size'],
'viewer_can_send_gift' => $fbUserProfile['viewer_can_send_gift'],
//extended permissions
'relationship_status' => $fbUserProfile['relationship_status'],
'hometown' => $fbUserProfile['hometown']['name'],
'languages' => implode(",", array_map(function($x) { return $x['name'];},$fbUserProfile['languages'])),//$fbUserProfile['languages'][0]['name'].",".$fbUserProfile['languages'][1]['name'].",".$fbUserProfile['languages'][2]['name'].",".$fbUserProfile['languages'][3]['name'].",".$fbUserProfile['languages'][4]['name'],
'likes' => implode(",", array_map(function($x){ return $x['name'];}, $fbUserProfile['likes']['data'])),
'favorite_athletes' => implode(",", array_map(function($x) { return $x['name'];},$fbUserProfile['favorite_athletes']))

Related

how to loop and array to create a TABLE in laravel with phpdocx

I am using phpdocx to generate an array with my data in a docx format.
$contact is an array of multiple object. Sometimes $contact contain 1 object, and sometimes more.
I want to make a loop, to add contact as much as I need.
My problem : For exemple, If I am doing this I will get an error like "Undefined array key 3" if my contact data only contain 3 object or less.
important : Here, if my datas contain 4 object (from 0 to 3 ) it will work but doesn't work when i have 2 objects.
$contact= array(
array(
'name' => $request->get('contact')[0]['name'],
'userName' => $request->get('contact')[0]['userName'],
'number' => $request->get('contact')[0]['number'],
'mail' => $request->get('contact')[0]['mail'],
),
array(
'name' => $request->get('contact')[1]['name'],
'userName' => $request->get('contact')[1]['userName'],
'number' => $request->get('contact')[1]['number'],
'mail' => $request->get('contact')[1]['mail'],
),
array(
'name' => $request->get('contact')[2]['name'],
'userName' => $request->get('contact')[2]['userName'],
'number' => $request->get('contact')[2]['number'],
'mail' => $request->get('contact')[2]['mail'],
),
array(
'name' => $request->get('contact')[3]['name'],
'userName' => $request->get('contact')[3]['userName'],
'number' => $request->get('contact')[3]['number'],
'mail' => $request->get('contact')[3]['mail'],
),
);
$docx->replaceTableVariable($contact, array('parseLineBreaks' => true));
what i am actually trying with no success for the moment : https://www.phpdocx.com/en/forum/default/topic/1773
I have make a loop and it is now working
$contactData = $request->get('contact');
$contactTab = array();
for ($i = 0; $i < count($contactData); $i++) {
$rowData = array(
'name' => $contactData[$i]['name'],
'userName' => $contactData[$i]['userName'],
'number' => $contactData[$i]['number'],
'mail' => $contactData[$i]['mail'],
);
$contactTab[] = $rowData;
}
$docx->replaceTableVariable($contactTab, array('parseLineBreaks' => true));

Identifying unknown structured data formats – what could be class-oriented JSON

I'm currently working with a Sophos UTM, pushing the wireless statistics to another platform and trying to digest this data format.
It's clearly structured and looks like class-oriented JSON, but cannot quite figure out what it is or how to convert it to something usable. Any ideas? I thought about just writing a JSON-converter in PHP, but I'm afraid that I might just be missing a puzzle piece.
{
'clients' => {
'0c:2c:54:xx:xx:xx' => {
'ap' => '',
'connected_time_sec' => 1720,
'connected_time_str' => '00:28:40',
'hwaddr' => '0c:2c:54:xx:xx:xx',
'ip' => '172.16.28.206',
'last_rxrate_bps' => '1048576',
'last_rxrate_str' => '1024.0 kbit/s',
'last_txrate_bps' => '6815744',
'last_txrate_str' => '6.5 Mbit/s',
'lastseen_str' => '2018-11-04 18:06:37',
'lastseen_ts' => 1541351197,
'mesh_id' => '',
'mesh_mode' => 'none',
'name' => 'HUAWEI_P20_Pro',
'radio_id' => '0',
'signal_per' => '39',
'ssid' => 'ssid',
'vendor' => 'unknown'
},
'44:d8:84:xx:xx:xx' => {
'ap' => 'A40001AXX8FXXXX',
'connected_time_sec' => 534992,
'connected_time_str' => '06:04:36:32',
'hwaddr' => '44:d8:84:xx:xx:xx',
'ip' => '172.16.28.149',
'last_rxrate_bps' => '1048576',
'last_rxrate_str' => '1024.0 kbit/s',
'last_txrate_bps' => '60607488',
'last_txrate_str' => '57.8 Mbit/s',
'lastseen_str' => '2018-11-04 20:44:28',
'lastseen_ts' => 1541360668,
'mesh_id' => '',
'mesh_mode' => 'none',
'name' => 'iMac-OBC',
'radio_id' => '0',
'signal_per' => '65',
'ssid' => 'ssid',
'vendor' => 'Apple'
}
},
'connected' => {
'A40001AXX8FXXXX' => {
'associated_clients' => [
'ab:cd:ef:gh:ij:kl',
'44:d8:84:xx:xx:xx',
],
'bss' => undef,
'id' => 'A40001AXX8FXXXX',
'ip' => '192.168.10.11',
'lan_mac' => '00:1a:8c:xx:xx:xx',
'location' => 'AP30',
'type' => 'AP30',
'wifi_mac' => '00:1a:8c:xx:xx:xx'
},
'A4000EASIJDFSDOI' => {
'associated_clients' => [],
'bss' => undef,
'id' => 'A4000EASIJDFSDOI',
'ip' => '192.168.10.12',
'lan_mac' => '00:1a:8c:xx:xx:xx',
'location' => 'AP30',
'type' => 'AP30',
'wifi_mac' => '00:1a:8c:xx:xx:xx'
}
},
'disconnected' => {},
'lastupdate' => 1541360678
}
Your sample data has 4 repairs to make on the road to valid json town.
Make the following replacements:
=> to :
' to "
remove all trailing , that are followed by zero or more whitespace characters then a ]
wrap your undef values in double quotes
Code: (Demo)
$almostjson = <<<ALMOSTJSON
...your input string
ALMOSTJSON;
$json = preg_replace(["~=>~", "~'~", "~,(?=\s*])~", "~:\s+\Kundef~"], [':', '"', '', '"$0"'], $almostjson);
var_export(json_decode($json, true));
Calling regex functions on strings that contain key-value relationships is vulnerable to unintended matching. This "solution" should be considered a "bandaid" until the source of the data can be improved. This solution may silently fail in the future if the wrong quality of text is in the string.

Having a hard time retrieving the customer_id getId() from createCustomer object to pass to createCustomerCard

Here is my code which is the example I used from here
$createcustomer_api = new \SquareConnect\Api\CustomersApi();
$createcustomer_result = $createcustomer_api->createCustomer(array(
'given_name' => 'Amelia',
'family_name' => 'Earhart',
'email_address' => 'Amelia.Earhart#example.com',
'address' => array(
'address_line_1' => '500 Electric Ave',
'address_line_2' => 'Suite 600',
'locality' => 'New York',
'administrative_district_level_1' => 'NY',
'postal_code' => '10003',
'country' => 'US'
),
'phone_number' => '1-555-555-0122',
'reference_id' => 'YOUR_REFERENCE_ID',
'note' => 'a customer'
));
If I print out the results I get
SquareConnect\Model\CreateCustomerResponse Object
(
[errors:protected] =>
[customer:protected] => SquareConnect\Model\Customer Object
(
[id:protected] => CBASEHtp6YVU8AirkMv1lrVMyoIgAQ
[created_at:protected] => 2017-09-27T23:19:44.62Z
[updated_at:protected] => 2017-09-27T23:19:44.62Z
[cards:protected] =>
[given_name:protected] => Amelia
[family_name:protected] => Earhart
[nickname:protected] =>
[company_name:protected] =>
[email_address:protected] => Amelia.Earhart#example.com
[address:protected] => SquareConnect\Model\Address Object
(
[address_line_1:protected] => 500 Electric Ave
[address_line_2:protected] => Suite 600
[address_line_3:protected] =>
[locality:protected] => New York
[sublocality:protected] =>
[sublocality_2:protected] =>
[sublocality_3:protected] =>
[administrative_district_level_1:protected] => NY
[administrative_district_level_2:protected] =>
[administrative_district_level_3:protected] =>
[postal_code:protected] => 10003
[country:protected] => US
[first_name:protected] =>
[last_name:protected] =>
[organization:protected] =>
)
[phone_number:protected] => 1-555-555-0122
[reference_id:protected] => YOUR_REFERENCE_ID
[note:protected] => a customer
[preferences:protected] => SquareConnect\Model\CustomerPreferences Object
(
[email_unsubscribed:protected] =>
)
[groups:protected] =>
)
)
Now I need to create the customer card to associate with the customer for future recurring payments.
$createcard_api = new \SquareConnect\Api\CustomersApi();
$createcard_result = $createcard_api->createCustomerCard($createcustomer_result->getId(), array(
'card_nonce' => $nonce,
'billing_address' => array(
'address_line_1' => '1455 Market St',
'address_line_2' => 'Suite 600',
'locality' => 'San Francisco',
'administrative_district_level_1' => 'CA',
'postal_code' => '94103',
'country' => 'US'
),
'cardholder_name' => 'Amelia Earhart'
));
From what I understand there is a built-in function with the square SDK that is getId() which according to this is called like $customer->getId(), but according to this I need to just add ->getId() to my createCustomer object.
So I am trying to call the getId() function as
$createcustomer_result->getId()
but in my code I am getting the error
Fatal error: Call to undefined method SquareConnect\Model\CreateCustomerResponse::getId()
How do I properly get the customer id from the createCustomer?
You've only got the response object from the API, a communication device. You need to first extract the created object from the response, then you can query it for the ID.
$customer = $createcustomer_result->getCustomer();
That should get you the actual customer object, then you can:
$customer_id = $customer->getId();
This is pretty common for API libraries. You can also query the response object for errors if they occur. When using these kinds of libraries, have a look inside the various classes and read through the functions, you can get a better idea of how you use them that way.

CI Active Record Query not updating

I Am trying to update tenders table in my db but for some reasons its updating the table with zeros.
After getting the last_query() string and running it from phpmyadmin window it updates successfully but using active records it does not.
Other queries are working properly apart from this.
What might be the problem with my code?
Here is my code
$data=array(
'tender_type_type_id' => $this->input->post('tender_type_id'),
'Description' => $this->input->post('tdescription'),
'obtaining_documents' => $this->input->post('obtaining_docs'),
'submission_process' => $this->input->post('submission_proc'),
'obtaining_documents' => $this->input->post('obtaining_docs'),
'applicationfee' => $this->input->post('applicationfee'),
'Location' => $this->input->post('location'),
'WebLink' => $this->input->post('url'),
'clossing_date' => $this->input->post('endson'),
'opening_date' => $this->input->post('openedon'),
'title' => $this->input->post('title'),
'publication_date' => date('Y-m-d H:i:s', time()),
'attachments' => $this->input->post('upload'),
'Organization_OrganizationID' => $this->input->post('organizationid'),
'tender_category_category_id' => $this->input->post('categoryid'),
'Towns_TownID' => $this->input->post('townid'),
'Accounts_AccountID' =>$this->input->post('accountid'),
'tender_status_status_id' => $this->input->post('tender_status_id'),
'Location' => $this->input->post('location'),
'clossing_date' => $this->input->post('endson'),
'opening_date' => $this->input->post('openedon'));
$id=$this->uri->segment(3);
$this->db->where('TenderID',$id);
$this->db->update('tenders',$data);
return print_r($this->db->last_query());

SOAP 4 set_relationship not working

After battling for getting more than 20 entries with get_entry_list, i'm now trying to use the SOAP API on SugarCRM 6.5 to set a relationship between two elements, created from a form on the user-land website.
The set_relationship method is described as following in the devs blog :
$response = set_relationship(session, module_name, module_id, link_field_name, related_ids, name_value_list, delete);
So here is the code which handles the request, assuming that another part of the code handles the security.
$values = array( 'id_frame' => $_POST['id_frame'],
'id_battery' => $_POST['id_battery'],
'reseller' => $_POST['reseller'],
'date_purchase' => $_POST['date_purchase'],
'products_versionning' => $_POST['product_purchased'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['name'],
'phone_home' => $_POST['phone'],
'email' => $_POST['email'],
'primary_address_street' => $_POST['address'],
'primary_address_street_2' => $_POST['address2'],
'primary_address_street_city' => $_POST['city'],
'primary_address_street_postalcode' => $_POST['zip'],
);
try{
$prod_register = $soapClient->set_entry(
$sessid,
'myco_product_register',
array( array('name' => 'id_frame', 'value' => $values['id_frame']),
array('name' => 'id_battery', 'value' => $values['id_battery']),
array('name' => 'date_purchase', 'value' => $values['date_purchase']),
array('name' => 'first_name', 'value' => $values['first_name']),
array('name' => 'last_name', 'value' => $values['last_name']),
array('name' => 'phone_home', 'value' => $values['phone_home']),
array('name' => 'email', 'value' => $values['email']),
array('name' => 'primary_address_street', 'value' => $values['primary_address_street']),
array('name' => 'primary_address_street_city', 'value' => $values['primary_address_street_city']),
array('name' => 'primary_address_street_postalcode','value' => $values['primary_address_street_postalcode']),
array('name' => 'description','value' => "Modèle : " . $values['products_versionning'] . "\nAcheté le " . $values['date_purchase'] . " à " . $values['reseller']),
)
);
$client = $soapClient->set_entry(
$sessid,
'Accounts',
array( array('name' => 'name', 'value' => $values['first_name'] . ' ' . $values['last_name']),
array('name' => 'billing_address_street', 'value' => $values['primary_address_street']),
array('name' => 'billing_address_city', 'value' => $values['primary_address_street_city']),
array('name' => 'billing_address_postalcode', 'value' => $values['primary_address_street_postalcode']),
)
);
$entry_id = $prod_register->id;
$relationship_parameters = array(
"module1" => "myco_product_register",
"module1_id" => array($entry_id),
"module2" => "myco_products_versionning",
"module2_id" => array($values['products_versionning'])
);
//Now i'm setting the relationships
$response = $soapClient->set_relationship($sessid, "myco_product_register", $entry_id,
'myco_products_versionning_id_c', $values['products_versionning'], array(), 0);
$response = $soapClient->set_relationship($sessid, "myco_product_register", $entry_id,
'myco_resellers_id_c', $values['reseller'], array(), 0);
Both set_entry requests work and return a working id, but no one of the relationships work ($responses contains a failed equal to 1). So that's not a connection problem or such.
Talking about the relationships, one guy from the devblog said that
there has to be a relationship between the two modules
there has to be at least one related field in the module which handle the relation, whose name you can find in the module's vardefs.php
and i have
A One-to-one relationship between the product_register module and both products_versionning and resellers
A related field in product_register for each related module.
What may i be missing ?
try checking the log file of SugarCRM, you should find some mistakes. I used this API to create a relationship between Contacts and Accounts, and working properly. On the logs might find the answer to the problem.
try {
$result = $this->soapClient->set_relationship($this->sessionId,
$accountModuleName, $accountId, $relationName, $contactsId);
$this->doEvent(self::EVENT_WS_OPERATION_CALL);
if ($result->created > 0 && $result->failed === 0) {
return true;
} else {
return false;
}

Categories