Integrating mailchimp with CRM - php

Need to get campaign_id with the list_id that I've got. My goal is to get all the campaign data and then sort out using the list_id. I have been able to retrieve the campaign response body, but somehow failing to get the campaign list_id. Any help or a different approach would be appreciated. Sharing my code and mailchimp api related reference.
MailChimp api ref:
"campaigns": [
{
"id": "42694e9e57",
"type": "regular",
"create_time": "2015-09-15T14:40:36+00:00",
"archive_url": "http://",
"status": "save",
"emails_sent": 0,
"send_time": "",
"content_type": "template",
"recipients": {
"list_id": "57afe96172", // this is required
"segment_text": ""
},
My Progress:
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns"); // gives a response consisting 3 rows, required value is in 1st row, which is an array
foreach ($MCcampaigninfo as $key => $value) {
if ($value[8]->'list_id' == $list_id) { //under the 'campaign'array, we need the 9th position property 'recipient'
$campaign_id = $value[12]->'id';
}
}
}

This code assumes the response of $mc_api->get is equal to the JSON you showed in your example
public static function getCampaignID($list_id) {
$campaigns = json_encode(self::$mc_api->get("/campaigns"), true);
$campaignIds = [];
foreach ($campaigns as $campaign) {
//if the list_id matches the current campaign recipients['list_id'] add to the array
if ($campaign['recipients']['list_id'] === $list_id) {
$campaignIds[] = $campaign['id'];
}
}
//return an array with campaignIds
return $campaignIds;
}

Got it working. The api structure seems different in reality from their documentation. Thanks for all the help. Posting my updated code.
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns");
foreach ($MCcampaigninfo as $key => $campaign) {
if($key == campaigns){
foreach ($campaign as $key2 => $clist) {
foreach ($clist as $key3 => $recip) {
if($key3 == id){
$campaign_id = $recip;
}
elseif($key3 == recipients){
foreach($recip as $key4 => $listid){
if($key4 == list_id){
if($listid == $list_id){
return $campaign_id;
}
}
}
}
}
}
}
}
}

Related

Update the Nested Json with another Nested Json using php

I am new to PHP and have little experience with PHP arrays. I have the nested JSON data and I want to update some data with new data by the field id. I am trying to create dynamic sections with fields. There is a section id and field id and the new data will check the old JSON data by section and field id and then update it. Below is my complete code.
OR any other better way to update it?
$old_data= '
{
"section_1":
[
{
"text":{"class":"mb-20","name":"text","id":"field-id-11","value":"value 01","placeholder":"Section placeholder"}
},
{
"textarea":{"class":"mb-20","name":"section_content","id":"field-id-12","value":"Section content 1","placeholder":"Section Content"}
}
],
"section_2":
[
{
"text":{"class":"mb-20","name":"text","id":"field-id-1","value":"value amir 1","placeholder":"Section placeholder"}
},
{
"textarea":{"class":"mb-20","name":"section_content","id":"field-id-2","value":"Section content 1","placeholder":"Section Content"}
}
]
}';
Here below is my new data coming from a section.
$new_data=
'{
"section_1":
[
{"type":"text","id":"field-id-11","value":"Foot Ball"},
{"type":"textarea","id":"field-id-12","value":"Awesome game!"}
],
"section_2":
[
{"type":"text","id":"field-id-1","value":"New Data"},
{"type":"textarea","id":"field-id-2","value":"Hello"}
]
}';
Here I am testing the old data with static new data and it is working fine. But I am confused how to marge the new data in the below foreach loop?
$sections = json_decode($old_data, true);
foreach ($sections as $section_id => &$section_fields)
{
if($section_id == 'section_2')
{
foreach ($section_fields as &$section_fields_array)
{
foreach ($section_fields_array as $section_field_name => &$section_field_data)
{
if($section_field_name == 'text' && $section_field_data['id'] == '3454gfdgdgtd')
{
$section_fields_array[$section_field_name]['value'] = "Foot Ball 2";
}
}
}
}
}
``
At least with a fresh mind, I just fix the code. Checking by field id and then updating it.
$new_sections = json_decode($new_data, true);
$sections = json_decode($old_data, true);
foreach ($new_sections as $new_section_id => &$new_section_fields)
{
foreach ($new_section_fields as $index => &$new_section_fields_data)
{
if($new_section_fields_data['id'] == $sections[$new_section_id][$index][$new_section_fields_data['type']]['id'])
{
$sections[$new_section_id][$index][$new_section_fields_data['type']]['value'] = $new_section_fields_data['value'];
}
}
}

Implementing filter of nested arrays in PHP/Wordpress

I have in the process of moving some code from the front-end (in JavaScript) to the server-side (which is PHP) where it will be filtered and sent out in an API call, and I can't seem to get the filter working properly on the back-end. The code takes an array of objects and filters it for the objects where a certain nested field (which is also an array of objects) contains certain values. The basic shape of the API:
{
"id": 1217,
"name": "Best product ever",
"tags": [
{
"id": 125,
"name": "Important Value",
"slug": "important-value"
},
{
"id": 157,
"name": "Value",
"slug": "value"
},
{
"id": 180,
"name": "Value",
"slug": "value"
},
{
"id": 126,
"name": "Value",
"slug": "value"
},
{
"id": 206,
"name": "Other Important Value",
"slug": "other-important-value"
}
}
The working JS code:
let productAttributes = ['important-value', 'value', 'value', 'value', 'other-important-value'];
filterResults(results) {
let filteredResults = results.filter(product => {
return product.tags.find(tag => {
return tag.slug === this.productAttributes[0];
});
});
if (this.productAttributes[0] !== 'certain important value') {
filteredResults = filteredResults.filter(product => {
return product.tags.find(tag => {
return tag.slug === this.productAttributes[4];
});
});
}
return filteredResults;
}
And the (not yet working) PHP code:
function get_awesome_products() {
$baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/?
consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page=';
for ($count = 1; $count <= 9; $count++ ) {
$request = wp_remote_get( $baseRequest . (string)$count);
$body = wp_remote_retrieve_body( $request );
$data = array_values( json_decode( $body, true ));
if ($count < 2) {
$completeProductList = $data;
} else {
$completeProductList = array_merge($completeProductList, $data);
}
}
// The code above this comment is doing what I expect, the code below is not.
$filteredProducts = null;
foreach ($completeProductList as &$product) {
$tagArray = $product['tags'];
if (in_array($reg_test_array[0], $tagArray, true) &&
in_array($reg_test_array[4], $tagArray, true))
{
array_push($filteredProducts, $product);
}
unset($product);
return new WP_REST_Response($filteredProducts, 200);
The impression I get is that I need to write a custom function to take the place of Array.prototype.find(), but I'm not strong in PHP and am having trouble wrapping my head around it.
EDIT: Edited to add example of object being filtered and additional PHP code
You could also use the PHP equivalent function array_filter (among a few other array-specific functions) for this task.
Example:
// Your 0 and 4 index values from $reg_test_array
$importantTags = [ "important-value", "other-important-value" ];
$filteredProducts = array_filter($completeProductList, function($product) use ($importantTags) {
return (bool)array_intersect($importantTags, array_column($product['tags'], 'slug'));
});
return new WP_REST_Response($filteredProducts , 200);
Sandbox
This should be equivalent to the JavaScript code you posted, but done without looping through the filtered results twice.
Without knowing the context of important-value and other-important-value, and how they come to be ordered in the $attributes array, it's a little difficult to improve upon the conditional checks used. What I've written thus far however feels like a code smell to me, because it's reliant hard coded values.
function filterResults(array $results, array $attributes)
{
return array_reduce($results, function ($filteredResults, $result) use ($attributes) {
// Extract tag slugs from result
$tagSlugs = array_column($result['tags'], 'slug');
// Append result to filtered results where first attribute exists in tag slugs;
// Or first attribute is not *other-important-value* and fourth attribute exists in tag slugs
if (in_array($attribute[0], $tagSlugs) && ($attribute[0] === 'other-important-value' || in_array($attribute[4], $tagSlugs))) {
$filteredResults[] = $result;
}
return $filteredResults;
}, []);
}

how to search in Json and get sub data [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
i have a json file of users with all descriptions and its hard to find them with data[2]. imagine in data[0]->users->data i have 3 user and i want to find name = "Stafin" to get description->data->instagram and get value. i'll give you a simple json data
{"data":[
{
"id":1,
"category_name":"Writers",
"users":{
"data":[{
"name":"Steve",
"id":"1",
"description":{
"data":[
{
"instagram":"steveid"
}
]
}
},{
"name":"Stafin",
"id":"2",
"description":{
"data":[
{
"instagram":"stafinid"
}
]
}
},{
"name":"Sara",
"id":"3",
"description":{
"data":[
{
"instagram":"saraid"
}
]
}
}]
}
}
]}
Code:
<?php
$str = file_get_contents('http://localhost/json/test.json');
$json = json_decode($str, true);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
return $key;
}
}
return null;
}
$id = searchForId('2', $json);
echo $id;
?>
note that: answer it in php language
sorry for my bad English language. if you didn't get that, just tell me to describe more
Your function searches for id, but you said you wanted to search for name. You can make the key another parameter of the function. Then you can use it to find the id in the data array, and the name in the users['data'] array.
function searchArray($searchkey, $searchval, $array) {
foreach ($array as $key => $val) {
if ($val[$searchkey] === $searchval) {
return $val;
}
}
return null;
}
foreach ($json['data'] as $data) {
$user = searchArray('name', 'Stafin', $data['users']['data']);
if ($user) {
echo "Found Stafin";
foreach ($user['description']['data'] as $desc) {
if (isset($desc['instagram'])) {
echo ", Instagram is {$desc['instagram']}";
break;
}
}
break;
}
}

PHP using json_encode, must output the specific data

I'm currently stuck at this scenario, now the other developer wants to output the API structure as seen on attached image.
json_required_format
But I tried as far as I can but I only got these result:
"all_projects": {
"TEST TOWNHOMES": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
}
]
},
"TEST HOMES": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST HOMES II": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST VILLAGE": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
},
{
"unit": "DUPLEX WITHOUT GARAGE 52.30"
}
]
}
I am using MVC framework,
This is my model looks like:
public function all_south_projects()
{
$this->db->distinct();
return $this->db->select('Project as project_name')->from('lots')
->where('available','YES')
->get()->result();
}
public function get_unit_types($projName)
{
$this->db->distinct();
return $this->db->select('UnitType as unit')->from('lots')
->where('Project',$projName)
->where('Available','YES')
->get()->result();
}
And then my controller is:
$resp = $this->MyModel->all_south_projects();
$test_array = array();
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
//var_dump($test_array);
$stat = 200;
$message = 'Successfully fetched.';
if(empty($test_array)){
$empty=json_decode('{}');
json_output2($stat,'all_projects',$message,$empty);
}else{
json_output2($stat,'all_projects',$message,$test_array);
}
json_output2 is on my helper to customize json format:
Here is my code:
function json_output2($statusHeader,$responseName,$message,$response)
{
$ci =& get_instance();
$ci->output->set_content_type('application/json');
$ci->output->set_status_header($statusHeader);
$ci->output->set_output(json_encode(array('status' =>
$statusHeader,'message' => $message,$responseName =>$response)));
}
NOTE: Scenario is:
The API must give all the projects having available units,
if the project is available, then it needs to get its corresponding available units to view. I know I can make another API call but this time, we need to improve the UX.
Can someone enlighten me to get through this? Thank you!
Change this part :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
To :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$test_array[] = [
"project_name" => $value->project_name,
"unit_types" => $units
];
}
You don't have to cast your associative array to object like you did there : $allunits = (object) $allunits; because an associative array will always be serialized as a JSON object (associative arrays do not exist in JSON).

php | dynamic api call

I am trying to create a dynamic endpoint for a API I am creating in order to include some data but only if it is required so I can use it in multiple places.
The idea is to have api.domain.com/vehicle to bring back basic vehicle information but if I did api.domain.com/vehicle?with=owners,history then the idea is to have a function which maps the owners and history to a class which will return data but only if it is required.
This is what I currently have.
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
Which will then call this function.
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
However, the response I'm getting is being nested within a index, which I don't want it to be. The format I want is...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
But the format I am getting is this...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
How would I do this so it doesn't return with the index?
Vehicle::history($id) seems to return ['history'=>['year' => '26/01/2018']], ...etc.
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
Or your methods should returns something like ['year' => '26/01/2018'] and use :
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}

Categories