Get fields of stdClass object one by one - php

I am getting response from SMS API call like below
stdClass Object (
[balance] => 3
[batch_id] => 289728321
[cost] => 2
[num_messages] => 2
[message] => stdClass Object (
[num_parts] => 1
[sender] => TXTLCL
[content] => This is test message from abc
)
[receipt_url] =>
[custom] =>
[messages] => Array (
[0] => stdClass Object (
[id] => 1172603746 [recipient] => 919796736174 )
[1] => stdClass Object (
[id] => 1172603747 [recipient] => 919858566712)
)
[status] => success
)
The code which I am trying to tweak is like below
if(count($this->capturedResponse) > 0)
{
foreach($this->capturedResponse as $response)
{
$balance = $response[0];
$batch_id = $response[1];
...
}
}
I am not able to separate the stdClass Object fields separately and put them in their corresponding variables.
Please Help !!!

Please try like this
$balance = $response->balance;
$batch_id = $response->batch_id;

The easiest way is to JSON-encode your object and then decode it back to an array:
$capturedResponse = (object) (array(
'balance' => 1,
'batch_id' => 289728321,
'cost' => 2,
'num_messages' => 2,
'message' => (object) (array(
'num_parts' => 1
))
));
$array = json_decode(json_encode($capturedResponse), True);
echo $array['balance'];

You need to use -> to get element from object, so use like this
$balance = $response->balance;
$batch_id = $response->batch_id;
Instead
$balance = $response[0];
$batch_id = $response[1];
...
To get content of message
$message = $response->message->content
Try yourself for messages by loop let us know if any problem
Update
$messagesObj = $response->messages;
$messagesArr = array();
foreach($messagesObj as $key=>$value){
$messagesArr[] = $value->recipient;
}
$messages = implode(",",$messagesArr);
You will get 919796736174, 919858566712 in $messages

Related

Get the highest, second highest and the lowest from the multidimensional array based on another value

In my code, I am getting an array like below
Array
(
[12247] => stdClass Object
(
[wid] => 12247
[uid] => 1626
[timestamp] => 1482021161
[weight_value] => 63.9
[nid] => 1195487
[source] => 0
[weight_entered] =>
)
[34843] => stdClass Object
(
[wid] => 34843
[uid] => 1632
[timestamp] => 1485298453
[weight_value] => 72.5
[nid] => 1206019
[source] => 8176
[weight_entered] =>
)
[35316] => stdClass Object
(
[wid] => 35316
[uid] => 1632
[timestamp] => 1485723529
[weight_value] => 54.2
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[35177] => stdClass Object
(
[wid] => 35177
[uid] => 1632
[timestamp] => 1485559176
[weight_value] => 53.3
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12248] => stdClass Object
(
[wid] => 12248
[uid] => 1633
[timestamp] => 1481662016
[weight_value] => 56.6
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
[12249] => stdClass Object
(
[wid] => 12249
[uid] => 1635
[timestamp] => 1479839680
[weight_value] => 54
[nid] => 1209357
[source] => 0
[weight_entered] =>
)
)
The array is order by the nid, timestamp, wid in descending order. I need to get an output array which will contain only the latest, second latest and the first weight values with the nid as an index. So that I will get the details of a particular nid only.
The output which I think about is like below and the logic behind that is
These multidimensional arrays have a value nid. I need to get the
latest, second latest and the first weight_value from a particular
nid. As the array is already sorted in descending order of time, I
just need to fetch the first, second and last values from each inner
array having common nid
Array
(
[1195487] => stdClass Object
(
[latest_weight] => 63.9
[second_latest_weight] =>
[first_weight] =>
)
[1206019] => stdClass Object
(
[latest_weight] => 72.5
[second_latest_weight] =>
[first_weight] =>
)
[1209357] => stdClass Object
(
[latest_weight] => 54.2
[second_latest_weight] => 53.3
[first_weight] => 54
)
)
I tried the code, but I am stuck up by not getting the proper logic to apply. Please help.
The code which I am trying is given below. But it is not full and not correct too.
if(!empty($history_details)){
$last_weight = 0;
$second_last_weight = 0;
$first_weight = 0;
$prev_nid = '';
$prev_wid = '';
$prev_count = 1;
foreach($history_details as $single_history){
if(empty($weight_array[$single_history -> nid]['field_weight_format'])){
$current_weight = $weight_array[$single_history -> nid]['field_weight_value']." lbs";
}
else{
$current_weight = str_replace('-', ' ', $weight_array[$single_history -> nid]['field_weight_format']);
}
if($prev_nid == '' || $prev_nid != $single_history -> nid){
$last_weight = $single_history -> weight_value;
if($prev_nid != $single_history -> nid){
$prev_count = 1;
}
}
else if($prev_count === 2){
$second_last_weight = $single_history -> weight_value;
$first_weight = $single_history -> weight_value;
}
else if($prev_count > 2 && $prev_nid != $single_history -> nid){
$first_weight = $history_details[$prev_wid] -> weight_value;
}
$prev_count++;
$prev_nid = $single_history -> nid;
$prev_wid = $single_history -> wid;
}
}
You can just sort by the weight within a group I guess.
function findInGroup($outerArray, $targetGroup) {
$array = array_filter($outerArray, function ($item) use ($targetGroup) {
return $item->nid == $targetGroup;
});
uasort($array,function ($a,$b) {
return $a->weight_value<=>$b->weight_value;
});
$first = reset($array);
$second = next($array);
$last = end($array);
return [ $first, $second, $last ];
}
Then you can do:
findInGroup($history_details,1209357);
Or you can do it for all groups via:
$keys = array_unique(array_map(function ($item) {
return $item->nid;
}, $history_details); //All distinct keys
$pluckedValues = array_map(function ($id) use ($history_details) {
return findInGroup($history_details, $id);
}, $keys); //Just the values for each distinct key
$values = array_combine($keys, $pluckedValues); //Combined with the key.
Of course this is not an optimal solution but would be a place to start.

How to 'SELECT' data from orient db and display it using php

i am trying to select inserted data from orient db database and to echo it out ?
how can i do this using php ?
This is what i have done so far
require('OrientDB/OrientDB.php');
$db = new OrientDB('localhost', 2424);
$connected = $db->connect('root', 'hello');
$config = $db->DBOpen('tabe', 'root', 'hello');
if($connected)
{
$records = $db->query("select from Nation");
echo $records;
}
else
{
die('Server Error');
}
it just prints 'Array' on screen
i am running a Apache php server on windows machine.
how can i get the data from the databse and print in on the website.
when i use for each loop to print out the element
my script just time out
$records = $db->query("select from Nation");
foreach ($records as $v)
echo $v;
if i use print_r($records);
it gives the following output
Array ( [0] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 169 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 169:0 [version] => 4 [content:OrientDBRecord:private] => Nation#in_partOf:%AQAAAAIAwQAAAAAAAAAAAMIAAAAAAAAAAA==;,Country_Name:"India",Iso_code:"IN" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [1] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 170 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 170:0 [version] => 4 [content:OrientDBRecord:private] => Nation#Country_Name:"United States of America",Iso_code:"US" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) [2] => OrientDBRecord Object ( [isParsed:OrientDBRecord:private] => [className:OrientDBRecord:private] => [type] => d [clusterID:OrientDBRecord:private] => 171 [recordPos:OrientDBRecord:private] => 0 [recordID:OrientDBRecord:private] => 171:0 [version] => 2 [content:OrientDBRecord:private] => Nation#Country_Name:"Canada",Iso_code:"CA" [data] => OrientDBData Object ( [data:OrientDBData:private] => Array ( ) [record:OrientDBData:private] => OrientDBRecord Object *RECURSION* ) ) )
how to convert it in to suitable form . like taking only names from it
this is my table
Better use PhpOrient Library it is the officially supported library by orient db
$client = new PhpOrient();
$client->hostname = 'localhost';
$client->port = 2424;
$client->username = 'your_username';
$client->password = 'your_password';
$client->connect();
$client->dbOpen('Your_db_name');
$query = "SELECT FROM NATION";
$result = $client->query($query);
$result = json_encode($result);
$result = json_decode($result);
foreach ($result as $row){
echo $row->oData->Country_Name;
echo $row->oData->Iso_code;
}
phporient : https://github.com/orientechnologies/PhpOrient.git
Print the result. Instead of echo
print_r($records);
In order to iterate over the result, either use foreach or for
First check if we have some results, using foreach as :
if(count($records) > 0){//check if we have a result
foreach($records as $value){//loop
print_r($value);
}
}

group array of php objects and sum by object key

I have an array of php objects that looks something like this:
Array
(
[0] => stdClass Object
(
[order_id] => 1513
[order_total] => 12500.00
[sales_rep] => Doe_John
)
[1] => stdClass Object
(
[order_id] => 1046
[order_total] => 3300.00
[sales_rep] => Doe_John
)
[2] => stdClass Object
(
[order_id] => 337
[order_total] => 4500.00
[sales_rep] => Mosby_Ted
)
)
I am trying to get an array that is set up more like this:
Array
(
[0] => stdClass Object
(
[sales_rep] => Doe_John
[total_sales] => 15800.00
)
[1] => stdClass Object
(
[sales_rep] => Mosby_Ted
[total_sales] => 4500.00
)
)
I want to combine all of the objects with the same "sales_rep" and get the sum of their associated "order_total", which you can see an example of in my desired array above. Any thoughts on how to accomplish this? I've been at it for hours now and have not been able to figure out a solution.
Thanks so much for the help!
try this
$tmp = array();
foreach($objs as $obj){ // where `$objs` is your objects
if(!in_array($obj->sales_rep,array_keys($tmp))){
$tmp[$obj->sales_rep] = (object)array(
'sales_rep' => $obj->sales_rep,
'total_sales' => $obj->order_total
);
}else{
$tmp[$obj->sales_rep]->total_sales += $obj->order_total;
}
}
print_r(array_values($tmp));
$obj0 = new StdClass();
$obj0->order_id = 1513;
$obj0->order_total = 12500.00;
$obj0->sales_rep = 'Doe_John';
$obj1 = new StdClass();
$obj1->order_id = 1046;
$obj1->order_total = 3300.00;
$obj1->sales_rep = 'Doe_John';
$obj2 = new StdClass();
$obj2->order_id = 337;
$obj2->order_total = 4500.00;
$obj2->sales_rep = 'Mosby_Ted';
$array = array(
$obj0,
$obj1,
$obj2,
);
$newArray = array();
foreach ($array as $item) {
if (array_key_exists($item->sales_rep, $newArray)) {
$newObj = $newArray[$item->sales_rep];
$newObj->order_total += $item->order_total;
} else {
$newObj = new StdClass();
$newObj->sales_rep = $item->sales_rep;
$newObj->order_total = $item->order_total;
$newArray[$newObj->sales_rep] = $newObj;
}
}
print_r(array_values($newArray));

Adding Elements To An StdClass Array - PHP / Codeigniter

I have an array that is an stdClass. The output of that array is as follows :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
)
What I would like to do is add two variables to this stdClass. They are "total_bookings" and "total_venues";
I currently am looping through the results and then getting a count to create the total. I would like to add those two vars to the end of that stdClass array.
My PHP is as follows :
$vendors = $this->po_model->get_all_vendors();
$this->template->set('total_vendors', count($vendors));
$count = 0;
foreach($vendors as $vendor)
{
$count++;
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$count]['total_venues'] = $total_venues;
$vendors[$count]['total_bookings'] = $total_bookings;
}
However, When I var_dump that my Array looks like this :
Array
(
[0] => stdClass Object
(
[vendor_id] => 1
[user_id] => 1
[date_created] => 2013-06-12 16:48:38
[date_edited] =>
[status] => active
[user_firstname] => Stuart
[user_surname] => Blackett
)
[1] => Array
(
[total_venues] => 6
[total_bookings] => 14
)
)
So my question is, How do I add total_venues and total_bookings to that stdClass()?
Thanks
$myArray[$indexOfObject]->total_venues = 6;
$myArray[$indexOfObject]->total_bookings= 14;
Your example:
foreach($vendors as $key => $vendor)
{
$total_venues = $this->po_model->get_count_venues($vendor->user_id);
$total_bookings = $this->po_model->get_count_bookings($vendor->user_id);
$vendors[$key]->total_venues = $total_venues;
$vendors[$key]->total_bookings = $total_bookings;
}
its an object, you should use object notations, not array notations. also change your move your count++ below these two instructions
$vendors[$count]->total_venues = $total_venues;
$vendors[$count]->total_bookings = $total_bookings;
$count++;

PHP/MySQL: Recreate multidimensional array from existing array

I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.

Categories