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));
Related
I have this array. I have tried a few things but not getting what I want.
I tried a foreach loop but it does not seem to do it easly and the process takes a long time.
stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[display_number] => 100140
[client] => stdClass Object
(
[name] => TAUQIR SHEIKH ET AL
)
)
[1] => stdClass Object
(
[display_number] => 100141
[client] => stdClass Object
(
[name] => YOLANDA SHEIKH ET AL
)
)
I want it to be one simple array
[0] => Array
(
[0] => 100140
[1] => TAUQIR SHEIKH ET AL
)
[1] => Array
(
[0] => 100141
[1] => YOLANDA SHEIKH ET AL
)
Ok So the old code works but now they updated the API and this made it worse. The response is now
(
[data] => Array
(
[0] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[display_number] => 100140
[client] => stdClass Object
(
[name] => TAUQIR SHEIKH ET AL
)
)
[1] => stdClass Object
(
[display_number] => 100141
[client] => stdClass Object
(
[name] => YOLANDA SHEIKH ET AL
)
)
I tried this with the new code... But the array is empty. Where am I going wrong?
//clean and make into an array
$matter_array = array();
if(!empty($response_Decode->data->data) &&
is_array($response_Decode->data->data)) {
foreach ($response_Decode->data->data as $info) {
$d = array();
$d[] = $info->display_number;
$d[] = $info->client->name;
$matter_array[] = $d;
}
}
print_r($matter_array); //For testing
die(); //For testing
I would recommend asking who/what process is populating your dataset first and possibly adjust it there.
If not available then looping is required.
$results = array();
if(!empty($object->data) && is_array($object->data)) {
foreach ($object->data as $info) {
$d = array();
$d[] = $info->display_number;
if(!empty($object->client)) {
$d[] = $object->client->name;
}
$results[] = $d;
}
}
print_r($results);
I'm paranoid with empty(). Code not tested but should get you on the right track.
SO you were close... Thank you.
//clean and make into an array
$matter_array = array();
if(!empty($resp->data) && is_array($resp->data)) {
foreach ($resp->data as $info) {
$d = array();
$d[] = $info->display_number;
$d[] = $info->client->name;
$matter_array[] = $d;
}
}
print_r($matter_array)
Ok so I just simplified the array... AND THAT WORKS!
//clean and make into an array
$response_Decode=$response_Decode->data;
$response_Decode=$response_Decode[0];
//print_r ($response_Decode);
//die(); //For testing
$matter_array = array();
if(!empty($response_Decode->data) && is_array($response_Decode->data)) {
foreach ($response_Decode->data as $info) {
$d = array();
$d[] = $info->display_number;
$d[] = $info->client->name;
$matter_array[] = $d;
}
}
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
Hi I have an array of object like this
$json = json_decode($featureJson);
//which returns below
Array
(
[0] => stdClass Object
(
[productID] => 1
[productName] => Toyo
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
[1] => stdClass Object
(
[productID] => 2
[productName] => Maze
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
)
and I have another array that needs to match the ID of $json(Array of Objects) and return its productName.
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = '';
foreach ($IdArray as $item) {
$foo .= '{' . $item . '},';
}
echo $foo;
$foo return {1,2},{2,1} and I match $json so will display - {Toyo,Maze},{Maze,Toyo}, how can I do that? I have some hint using array_map()
but still got no idea to match in objects.
It's easier if you separate an array for the names first.
<?php
$featureJson = '[{"productID":1,"productName":"Toyo","assessments":[{"answer":"Yes"},{"answer":"No"}]},{"productID":2,"productName":"Maze","assessments":[{"answer":"Yes"},{"answer":"Yes"}]}]';
$json = json_decode($featureJson);
// Make an array of names
$names = [];
foreach($json as $products){
$names[$products->productID] = $products->productName;
};
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = [];
foreach ($IdArray as $ids) {
$ids = explode(',',$ids);
$fooItem = [];
foreach($ids as $id){
$fooItem[] = $names[$id];
}
$foo[]= '{' . implode(',',$fooItem) . '}'; }
echo implode(',',$foo);
Result:
{Toyo,Maze},{Maze,Toyo}
Check here
I have spent the whole day since morning to handle this without the solution.
I have these data comes from database. I use PHP PDO connection.
Array (
[0] => stdClass Object ( [testing_id] => 4 [testing_name] => please [testing_location] => kjnkdsnkdnskjndkjsndjknskdnsk )
[1] => stdClass Object ( [testing_id] => 3 [testing_name] => please [testing_location] => jknds ndns )
[2] => stdClass Object ( [testing_id] => 2 [testing_name] => please [testing_location] => be done to me ) )
I want to rename keys in objects instead of testing_id to be just id, testing_name to be name etc.
I have write number of functions like this below
function remove_keys($arr, $table) {
$object = new stdClass();
foreach ($arr as $key => $val) {
$x = (array) $val;
foreach ($x as $key2 => $value) {
$new_key = str_replace($table, '', $key2);
$object->$new_key = $value;
}
}
return $object;
}
and this
function replaceKey(&$array,$table) {
$x = array();
foreach($array as $k => $v){
$new_key = str_replace($table, '', $k);
array_push($x, $new_key);
}
$array = array_combine($x, $array);
return $array;
}
In all cases, I get only one object result instead of renaming the whole object
stdClass Object ( [id] => 2 [name] => please [location] => be done to me )
How can I rename each index in object and get the full object renamed? Any help please
I need the output to be like this
Array (
[0] => stdClass Object ( [id] => 4 [name] => please [location] => kjnkdsnkdnskjndkjsndjknskdnsk )
[1] => stdClass Object ( [id] => 3 [name] => please [location] => jknds ndns )
[2] => stdClass Object ( [id] => 2 [name] => please [location] => be done to me ) )
I have searched here without any similar solution
You are overwriting the object value in the foreach:
$object->$new_key = $value;
$object is always the same variable, try something like this:
function remove_keys($arr, $table) {
$temp_array = array();
foreach ($arr as $key => $val) {
$object = new stdClass();
$x = (array) $val;
foreach ($x as $key2 => $value) {
$new_key = str_replace($table, '', $key2);
$object->$new_key = $value;
}
$temp_array[] = $object;
}
return $temp_array;
}
This will give you back an array of objects.
I'm trying to get information from the $array1 below.
I'm getting with no problems venue's name and location address by doing:
$array2 = array();
$array3 = array();
foreach($array1 as $item){
$array2[] = $item->venue->name;
$array3[] = $item->venue->location->address;
}
But now I need to get the photos url and I don't know how to do it.
Thanks a million!
$array1:
Array
(
[0] => stdClass Object
(
[venue] => stdClass Object
(
[name] => a name
[location] => stdClass Object
(
[address] => main street
)
)
[photos] => stdClass Object
(
[count] => 1
[items] => Array
(
[0] => stdClass Object
(
[url] => http://folder/photo1.jpg
.
.
)))
.
.
$array1[0]->photos->items[0]->url
Remember - you access arrays with [index] parenthesis, objects with -> arrows.
Untested code:
$array2 = array();
$array3 = array();
$photos = array();
foreach($array1 as $item){
$array2[] = $item->venue->name;
$array3[] = $item->venue->location->address;
$item_photo_urls = array();
foreach($item->photos->items as $photo){
$item_photo_urls[] = $photo->url;
}
$photos[] = $item_photo_urls;
}
Now you have a third array called photos , which contains all the photo urls.
Try this :
$url = $item->photos->items[0]->url;