How to loop and get the values from second array in sequence - php

This is the Array I want to loop Into Events Index and get all the context print out of it how can i do this
Here is the Array Code Which i am trying to loop
[1] => stdClass Object
(
[id] => RPDNLNYO6U
[active] =>
[events] => Array
(
[0] => stdClass Object
(
[id] => RPDNLNYO6U_1
[created_at] => 2023-02-06T10:55:42.501003Z
[visibility] => all
[text] => Hi
[author_id] => 170bdd03-a163-49e9-4295-11fae376ff0e
)
[1] => stdClass Object
(
[id] => RPDNLNYO6U_2
[created_at] => 2023-02-06T10:55:44.102000Z
[visibility] => all
[text] => I need help
[author_id] => 170bdd03-a163-49e9-4295-11fae376ff0e
)
[2] => stdClass Object
(
[id] => RPDNLNYO6U_3
[created_at] => 2023-02-06T11:06:11.002000Z
[visibility] => agents
[type] => system_message
[text] => Chat is idle due to 10 minutes of inactivity
[system_message_type] => routing.idle
[text_vars] => stdClass Object
(
[duration] => 10
)
)
[3] => stdClass Object
(
[id] => RPDNLNYO6U_4
[created_at] => 2023-02-06T11:11:14.002000Z
[visibility] => all
[type] => system_message
[text] => Chat archived due to 15 minutes of inactivity
[system_message_type] => routing.archived_inactive
[text_vars] => stdClass Object
(
[duration] => 15
)
)
)
)

You can use a foreach loop in PHP to loop through the array and get all the context you need.
$array = [1 => (object) [
'id' => 'RPDNLNYO6U',
'active' => '',
'events' => [
(object) [
'id' => 'RPDNLNYO6U_1',
'created_at' => '2023-02-06T10:55:42.501003Z',
'visibility' => 'all',
'text' => 'Hi',
'author_id' => '170bdd03-a163-49e9-4295-11fae376ff0e'
]
]
]];
foreach ($array as $object) {
$id = $object->id;
$active = $object->active;
foreach ($object->events as $event) {
$event_id = $event->id;
$created_at = $event->created_at;
$visibility = $event->visibility;
$text = $event->text;
$author_id = $event->author_id;
echo "Event ID: $event_id, Created At: $created_at, Visibility: $visibility, Text: $text, Author ID: $author_id\n";
}
}
This will loop through the outer array and print out all the context for each event.

Related

Retrieve a value from JSON Object using PHP (Shiprocket API)

I am getting below json data thru Shiprocket API. Now I want to extract value of below variables in PHP code from this json.
I have tried to use json_decode but it did not work and show null value:
$data = json_decode($json);
$sr_status = $data['shipment_status'];
Please suggest the code to retrieve below variables value.
shipment_status , awb_code , courier_company_id
Array
(
[0] => stdClass Object
(
[tracking_data] => stdClass Object
(
[track_status] => 1
[shipment_status] => 7
[shipment_track] => Array
(
[0] => stdClass Object
(
[id] => 180339484
[awb_code] => 11150911492
[courier_company_id] => 55
[shipment_id] => 1711169662
[order_id] => 233223781187
[pickup_date] => 2023-01-11 03:02:00
[delivered_date] => 2023-01-16 12:22:00
[weight] => 0.25
[packages] => 1
[current_status] => Delivered
[delivered_to] => Solapur
[destination] => Solapur
[consignee_name] => ABC
[origin] => Ludhiana
[courier_agent_details] =>
[edd] =>
)
)
[shipment_track_activities] => Array
(
[0] => stdClass Object
(
[date] => 2023-01-16 12:22:00
[status] => 000-T-DL
[activity] => SHIPMENT DELIVERED
[location] => SOLAPUR
[sr-status] => 7
[sr-status-label] => DELIVERED
)
[1] => stdClass Object
(
[date] => 2023-01-16 11:34:00
[status] => 002-S-UD
[activity] => SHIPMENT OUTSCAN
[location] => SOLAPUR
[sr-status] => 17
[sr-status-label] => OUT FOR DELIVERY
)
)
[track_url] => https://shiprocket.co//tracking/11150911492
[etd] => 2023-01-14 17:02:00
[qc_response] => stdClass Object
(
[qc_image] =>
[qc_failed_reason] =>
)
)
)
)
you can try this:
$array = ...; // Your array here
$data= json_decode($array);
$shipment_status = $data[0]->tracking_data->shipment_status;
$awb_code = $data[0]->tracking_data->shipment_track[0]->awb_code;
$courier_company_id = $data[0]->tracking_data->shipment_track[0]->courier_company_id;
Or use $data = json_decode($json,true); which return an array where you can use
foreach($data as $val) {
$shipment_status = $val['tracking_data']['shipment_status'];
foreach ($val['shipment_track'] as $value) {
$awb_code = $value['awb_code'];
$courier_company_id = $value['courier_company_id'];
}
}

How to split array data returned from json string in php

I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}

I got this response from cleeng API ; how to convert this response to JSON

Cleeng_Entity_Collection Object
(
[entityType:protected] => Cleeng_Entity_SubscriptionOffer
[items:protected] => Array
(
[0] => Cleeng_Entity_SubscriptionOffer Object
(
[id:protected] => S955494970_US
[publisherEmail:protected] => vidya+mtc#ooyala.com
[url:protected] =>
[title:protected] => Annual subscription
[description:protected] =>
[period:protected] => year
[price:protected] => 49.99
[applicableTaxRate:protected] => 0
[currency:protected] => USD
[accessToTags:protected] => Array
(
[0] => d962607d3d4c4e3c98a343c7bcb64027
)
[active:protected] => 1
[createdAt:protected] => 1473681112
[updatedAt:protected] => 1473858745
[geoRestrictionEnabled:protected] =>
[geoRestrictionType:protected] =>
[geoRestrictionCountries:protected] => Array
(
)
[pending:protected] =>
[country] => US
[socialCommissionRate] => 0
[averageRating] => 4
[contentType] =>
[freePeriods] => 0
[freeDays] => 0
[expiresAt] =>
)
)
[totalItemCount:protected] => 5
[pending:protected] =>
)
All you need to do is just convert the Collection to a Regular Array and then json_encode() the Result like so:
<?php
$entityCollection = "???"; // THIS IS THE DATA FROM Cleeng_Entity_Collection Object
$entityArray = $entityCollection->toArray();
$entityJSON = json_encode($entityArray);

Array PHP, Check if exist multiple elements to another array

I have a question about this:
I have two array, one is static, and one can be updated by the user...
I would like to check for every id from the static array if exist the id to the other array, and if exsist, do something, if doesn't exist (when finish to check) pass to other ID etc...
now, the arrays are these:
user array (the user unlock 2 achievement):
Array (
[0] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 644081262362202
[title] => Achievement 2
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement2.html
)
)
[id] => 104693166566570
)
[1] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 968802826528055
[title] => Achievement 1
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement1.html
)
)
[id] => 104023386633548
)
)
the static Array (have 6 achievement saved):
Array (
[0] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement2
[title] => Achievement 2
[id] => 644081262362202
)
[1] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement3
[title] => Achievement 3
[id] => 912599152147444
)
[2] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement5
[title] => Achievement 5
[id] => 913757345379232
)
[3] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement6
[title] => Achievement 6
[id] => 921989084564878
)
[4] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement1
[title] => Achievement 1
[id] => 968802826528055
)
[5] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement4
[title] => Achievement 4
[id] => 1149671038394021
)
)
now, I use this script to echo the final output like the picture (results is the static array):
if (empty($results)) {
//echo 'noAchievement for the app';
} else {
foreach ($results as $result) {
$totalAchievementsApp .= ' [["' . "0" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";
}
}
now, How I can do to check inside the this script? I know I have to add another if inside the else to check if the ID is = to other ID, but I don't know how, I'm a little bit confused... I would like to check if the id of the static array exist in the other array, and if exsist, do this:
**$totalAchievementsApp .= ' [["' . "1" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";**
Thank you very much :)
If I understand correctly, you want to indicate for each entry in the static array whether its ID exists in the user array.
You can use array_column to generate an array of all IDs in the user array. Then use in_array to check if each static ID exists in that array. Set a value to 1 if its found and 0 if its not found.
For the sake of example, I've generated a new final output array. But you could just add the "found" value to each entry of the the static array.
<?php
$static=array(
array('point'=>50,'title'=>'TITLE 1','id'=>54632),
array('point'=>50,'title'=>'TITLE 2','id'=>54344),
array('point'=>50,'title'=>'TITLE 3','id'=>34225),
array('point'=>50,'title'=>'TITLE 4','id'=>2323245),
array('point'=>50,'title'=>'TITLE 5','id'=>23872445),
);
$user=array(
array('id'=>2323245,'title'=>'TITLE 1','point'=>50),
array('id'=>54344,'title'=>'TITLE 2','point'=>50),
array('id'=>34225,'title'=>'TITLE 3','point'=>50)
);
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],array_column($user,'id'))?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'point'=>$entry['point']
);
}
echo"<pre>".print_r($final,true)."</pre>";
With your data, the output is:
Array
(
[0] => Array
(
[found] => 0
[id] => 54632
[title] => TITLE 1
[point] => 50
)
[1] => Array
(
[found] => 1
[id] => 54344
[title] => TITLE 2
[point] => 50
)
[2] => Array
(
[found] => 1
[id] => 34225
[title] => TITLE 3
[point] => 50
)
[3] => Array
(
[found] => 1
[id] => 2323245
[title] => TITLE 4
[point] => 50
)
[4] => Array
(
[found] => 0
[id] => 23872445
[title] => TITLE 5
[point] => 50
)
)
EDIT
Given the more complex structure of your actual arrays, I nested several array_column functions to access the deeper "data > achievement > id" keys in your user array:
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
See the example below:
// initialize the "static" and "user" arrays
$static=array (
0 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement2',
'title' => 'Achievement 2',
'id' => 644081262362202
),
1 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement3',
'title' => 'Achievement 3',
'id' => 912599152147444
),
2 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement5',
'title' => 'Achievement 5',
'id' => 913757345379232
),
3 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement6',
'title' => 'Achievement 6',
'id' => 921989084564878
),
4 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement1',
'title' => 'Achievement 1',
'id' => 968802826528055
),
5 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement4',
'title' => 'Achievement 4',
'id' => 1149671038394021
)
);
$user=array(
0=>array(
'data' => array(
'importance' => 0,
'achievement' => array (
'id' => 644081262362202,
'title' => 'Achievement 2',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement2.html'
)
),
'id' => 104693166566570
),
1 => array (
'data' => array (
'importance' => 0,
'achievement' => array (
'id' => 968802826528055,
'title' => 'Achievement 1',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement1.html'
)
),
'id' => 104023386633548
)
);
// build array of user achievement IDs
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
// generate final array, with "found" values
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],$user_achvmts)?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'description'=>$entry['description'],
'points'=>$entry['data']['points']
);
}
echo"<pre>".print_r($final,true)."</pre>";
The result is:
Array
(
[0] => Array
(
[found] => 1
[id] => 644081262362202
[title] => Achievement 2
[description] => you unlock the achievement2
[points] => 50
)
[1] => Array
(
[found] => 0
[id] => 912599152147444
[title] => Achievement 3
[description] => you unlock the achievement3
[points] => 50
)
[2] => Array
(
[found] => 0
[id] => 913757345379232
[title] => Achievement 5
[description] => you unlock the achievement5
[points] => 50
)
[3] => Array
(
[found] => 0
[id] => 921989084564878
[title] => Achievement 6
[description] => you unlock the achievement6
[points] => 50
)
[4] => Array
(
[found] => 1
[id] => 968802826528055
[title] => Achievement 1
[description] => you unlock the achievement1
[points] => 50
)
[5] => Array
(
[found] => 0
[id] => 1149671038394021
[title] => Achievement 4
[description] => you unlock the achievement4
[points] => 50
)
)
Note that array_column is only available in PHP >= 5.5.0. For older versions, see the Recommended userland implementation for PHP lower than 5.5.
As an alternative to array_column, you could use array_map to build an array of the user IDs:
$user_achvmts = array_map( function($v) {return $v['data']['achievement']['id'];}, $user);
Or even just iterate through the user array:
$user_achvmts=[];
foreach ($user as $v) { $user_achvmts[]=$v['data']['achievement']['id']; }

How do I extract the details from a PHP object?

I'm working with an object that returns information in a format like the following... I've removed some details where the information gets a little repetitive to save some space.
ISC_QUOTE_ITEM Object (
[type:protected] => 1
[id:protected] => 4cff5974138c9
[hash:protected] => cd2a8393493a286cf1fe97d92a947719
[productData:protected] =>
[productId:protected] => 28
[variationId:protected] => 0
[variationOptions:protected] => Array ( )
[quantity:protected] => 1
[originalOrderQuantity:protected] => 0
[name:protected] => Mac Pro
[basePrice:protected] => 2799.0000
[sku:protected] =>
[wrapping:protected] => Array ( )
[configuration:protected] => Array ( )
[eventDate:protected] => Array ( )
[eventName:protected] =>
[parentId:protected] =>
[quote:protected] => ISC_QUOTE Object (
[customerId:protected] =>
[customerGroupId:protected] =>
[discounts:protected] => Array ( )
[addresses:protected] => Array (
[4cff2f55b0fcd] => ISC_QUOTE_ADDRESS_SHIPPING Object (
[shippingMethod:protected] =>
[shippingCache:protected] =>
[handlingCost:protected] => 0
[quote:protected] => ISC_QUOTE Object *RECURSION*
[type:protected] => shipping
[id:protected] => 4cff2f55b0fcd
[firstName:protected] => asd
[lastName:protected] => asd
[company:protected] => asd
[phone:protected] => asd
[email:protected] => sz#gmail.com
[address1:protected] => asd
[address2:protected] =>
[zip:protected] => 62990
[city:protected] => asd
[state:protected] => Array (
[id] => 0
[iso2] =>
[name] => asd
)
[country:protected] => Array (
[id] => 99
[name] => India
[iso2] => IN
)
[cachedTotals:protected] => Array ( )
[customFields:protected] => Array ( )
[saveAddress:protected] =>
[customerAddressId:protected] => 0
)
[4cff2f55cc2b6] => ISC_QUOTE_ADDRESS Object (
[handlingCost:protected] =>
[quote:protected] => ISC_QUOTE Object *RECURSION*
[type:protected] => billing
[id:protected] => 4cff2f55cc2b6
[firstName:protected] => asd
[lastName:protected] => asd
[company:protected] => asd
[phone:protected] => asd
[email:protected] => sz#gmail.com
[address1:protected] => asd
[address2:protected] =>
[zip:protected] => 62990
[city:protected] => asd
[state:protected] => Array (
[id] => 0
[iso2] =>
[name] => asd
)
[country:protected] => Array (
[id] => 99
[name] => India
[iso2] => IN
)
[cachedTotals:protected] => Array ( )
[customFields:protected] => Array ( )
[saveAddress:protected] =>
[customerAddressId:protected] => 0
)
)
[coupons:protected] => Array ( )
[giftCertificates:protected] => Array ( )
[items:protected] => Array (
[0] => ISC_QUOTE_ITEM Object (
[type:protected] => 1
[id:protected] => 4cff2f55b11d2
[hash:protected] => 587e0ee453488554f782b20f3c928916
[productData:protected] =>
[productId:protected] => 24
[variationId:protected] => 0
[variationOptions:protected] => Array ( )
[quantity:protected] => 3
[originalOrderQuantity:protected] => 0
[name:protected] => Apple iPod Socks
[basePrice:protected] => 29.0000
[sku:protected] =>
[wrapping:protected] => Array ( )
[configuration:protected] => Array ( )
[eventDate:protected] => Array ( )
[eventName:protected] =>
[parentId:protected] =>
[quote:protected] => ISC_QUOTE Object *RECURSION*
[discounts:protected] => Array ( )
[isCustomPrice:protected] =>
[addressId:protected] => 4cff2f55b0fcd
[cachedTotals:protected] => Array ( )
[inQuote:protected] => 1
[inventoryChecking:protected] => 1
[weight:protected] => 1.0000
[fixedShippingCost:protected] => 0.0000
)
[1] => ISC_QUOTE_ITEM Object (
[type:protected] => 1
[id:protected] => 4cff58167d29f
[hash:protected] => 1da6aa898763172b8f7b9d8097d37f42
[productData:protected] =>
[productId:protected] => 23
[variationId:protected] => 0
[variationOptions:protected] => Array ( )
[quantity:protected] => 1
[originalOrderQuantity:protected] => 0
[name:protected] => Apple In-Ear Headphones with Remote and Mic
[basePrice:protected] => 79.0000
[sku:protected] =>
[wrapping:protected] => Array ( )
[configuration:protected] => Array ( )
[eventDate:protected] => Array ( )
[eventName:protected] =>
[parentId:protected] =>
[quote:protected] => ISC_QUOTE Object *RECURSION*
[discounts:protected] => Array ( )
[isCustomPrice:protected] =>
[addressId:protected] => 4cff2f55b0fcd
[cachedTotals:protected] => Array ( )
[inQuote:protected] => 1
[inventoryChecking:protected] => 1
[weight:protected] => 2.0000
[fixedShippingCost:protected] => 0.0000
)
[2] => ISC_QUOTE_ITEM Object *RECURSION*
)
[isSplitShipping:protected] =>
[cachedTotals:protected] => Array ( )
[hasFreeShipping:protected] =>
[appliedStoreCredit:protected] => 0
[appliedDiscountRules:protected] => Array ( )
[customerMessage:protected] =>
[staffNotes:protected] =>
[orderStatus:protected] => 0
[orderId:protected] =>
[discountsEnabled:protected] => 1
)
[discounts:protected] => Array ( )
[isCustomPrice:protected] =>
[addressId:protected] => 4cff2f55b0fcd
[cachedTotals:protected] => Array ( )
[inQuote:protected] => 1
[inventoryChecking:protected] => 1
[weight:protected] => 3.0000
[fixedShippingCost:protected] => 0.0000
)
I need to extract details such as ID, name, etc. so that it reads 4cff5974138c9, Mac Pro, etc. respectively. How can I do that?
You need to call a function of that class (of which ISC_QUOTE_ITEM is an object - say MyClass ) which returns the protected variable
Edit
It can be accessed. I was correct.
Like this -
Add a function inside your class MyClass if you don't already have one.
public function getName()
{
return $this->name;
}
And then in your code you can do this:-
echo $obj->getName();
Read http://php.net/manual/en/language.oop5.visibility.php for details on visibility of types of variables
You can do this by using the reflector construct:
Example taken from http://www.php.net/manual/en/reflectionclass.getproperties.php:
<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$foo = new Foo();
$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
foreach ($props as $prop) {
print $prop->getName() . "\n";
}
var_dump($props);
?>
As you can see also the protected $bar is returned :) And have a look at http://www.php.net/manual/en/reflectionproperty.getvalue.php#98643 there it is shown how to return the value of a protected attribute.

Categories