This question already has answers here:
stdClass object and foreach loops
(5 answers)
Closed 4 months ago.
I have an object like this:
stdClass Object
(
[_count] => 10
[_start] => 0
[_total] => 37
[values] => Array
(
[0] => stdClass Object
(
[_key] => 50180
[group] => stdClass Object
(
[id] => 50180
[name] => CriticalChain
)
)
[1] => stdClass Object
(
[_key] => 2357895
[group] => stdClass Object
(
[id] => 2357895
[name] => Data Modeling
)
)
[2] => stdClass Object
(
[_key] => 1992105
[group] => stdClass Object
(
[id] => 1992105
[name] => SQL Server Users in Israel
)
)
[3] => stdClass Object
(
[_key] => 37988
[group] => stdClass Object
(
[id] => 37988
[name] => CDO/CIO/CTO Leadership Council
)
)
[4] => stdClass Object
(
[_key] => 4024801
[group] => stdClass Object
(
[id] => 4024801
[name] => BiT-HR, BI & IT Placement Agency
)
)
[5] => stdClass Object
(
[_key] => 37845
[group] => stdClass Object
(
[id] => 37845
[name] => Israel Technology Group
)
)
[6] => stdClass Object
(
[_key] => 51464
[group] => stdClass Object
(
[id] => 51464
[name] => Israel DBA's
)
)
[7] => stdClass Object
(
[_key] => 66097
[group] => stdClass Object
(
[id] => 66097
[name] => SQLDBA
)
)
[8] => stdClass Object
(
[_key] => 4462353
[group] => stdClass Object
(
[id] => 4462353
[name] => Israel High-Tech Group
)
)
[9] => stdClass Object
(
[_key] => 4203807
[group] => stdClass Object
(
[id] => 4203807
[name] => Microsoft Team Foundation Server
)
)
)
)
I need to get the id and name in an HTML table, but I seem to have a hard time iterating through this object. TIA. I understand that I need to get to the Values Array, and then to the group object, but I trip over the transitions between object and array and foreach vs index based iteration.
For example I tried this:
foreach ($res as $values) { print "\n"; print_r ($values); }
It iterates trough the object, but it also gives me useless
10 0 37
echo "<table>"
foreach ($object->values as $arr) {
foreach ($arr as $obj) {
$id = $obj->group->id;
$name = $obj->group->name;
$html = "<tr>";
$html .= "<td>Name : $name</td>";
$html .= "<td>Id : $id</td>";
$html .= "</tr>";
}
}
echo "</table>";
Since this is the top result in Google if you search for iterate over stdclass it may be helpful to answer the question in the title:
You can iterate overa stdclass simply by using foreach:
$user = new \stdClass();
$user->flag = 'red';
foreach ($user as $key => $value) {
// $key is `flag`
// $value is `red`
}
function objectToArray( $data )
{
if ( is_object( $data ) )
$d = get_object_vars( $data );
}
Convert the Object to array first like:
$results = objectToArray( $results );
and use
foreach( $results as result ){... ...}
I know it's an old post , but for sake of others:
when working with stdClass you should use Reflections:
$obj = new ReflectionObject($object);
$propeties = $obj->getProperties();
foreach($properties as $property) {
$name = $property->getName(); <-- this is the reflection class
$value = $object->$name; <--- $object is your original $object
here you need to handle the result (store in array etc)
}
foreach($res->values as $value) {
print_r($value);
}
Related
trying to filter data from std object to get result only with status = Active
here is my data =
$newresults =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30509
[status] => InActive
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
in foreach loop i need to get new array of std object with status = active only
so far i am trying to do this with
foreach ($newresults as $key => $value) {
if($value->status == 'Inactive')
unset($newresults[$key]);
}
$newresults[]=$value;
}
return $newresults;
thanks in advance i am sure i can do it this way but i might be doing mistake somewhere
expected output =
array {
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[2] => stdClass Object
(
[id] => 30510
[status] => Active
)
}
You could just use array_filter:
$newresults = array_filter($newresults, function ($v) { return $v->status == 'Active'; });
print_r($newresults);
Output:
Array
(
[1] => stdClass Object
(
[id] => 30508
[status] => Active
)
[3] => stdClass Object
(
[id] => 30510
[status] => Active
)
)
Demo on 3v4l.org
If you want the array to be re-indexed starting at 0, just use array_values on the result.
That should work where you just remove those "Inactive" ones.
foreach ($newresults as $key => $value) {
if ($value->status == 'Inactive') {
unset($newresults[$key]);
}
}
I'm trying to group the arrays of a query, using the PHP foreach loop, to a group of objects without sub objects. But I'm not getting it, I've tried it in several ways. I'm using the following loop with foreach:
public function array_to_object($array)
{
$obj = new stdClass;
foreach($array as $k => $v) {
if(is_array($v)){
$obj->{$k} = $this->array_to_object($v); //RECURSION
} else {
$obj->{$k} = $v;
}
}
return $obj;
}
$users = $this->array_to_object($users);
print_r((array)$users);
I have this result:
Array
(
[0] => stdClass Object
(
[_id] => 12
[username] => lucaspedro
[first_name] => Lucas
[user_role] => stdClass Object
(
[ur_name] => Admin
)
)
[1] => stdClass Object
(
[_id] => 32
[username] => joaosilva
[first_name] => Joao
[user_role] => stdClass Object
(
[ur_name] => Member
)
)
)
But I need this result:
Array
(
[0] => stdClass Object
(
[_id] => 12
[username] => lucaspedro
[first_name] => Lucas
[ur_name] => Admin
)
[1] => stdClass Object
(
[_id] => 32
[username] => joaosilva
[first_name] => Joao
[ur_name] => Member
)
)
A simple foreach can do the trick for you.
foreach($array as $k=>$v){
$array[$k]->ur_name = $v->user_role->ur_name;
unset($array[$k]->user_role);
}
print_r($array);
I'm trying to sort the following data by the date in the key and the value of Name.
The aim is to a get nice date ordered array with all the Names from the inner array in alphabetical order.
Array
(
[2017-07-27] => Array
(
[0] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Orange
)
)
[4] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Apple
)
)
)
[2017-07-22] => Array
(
[6] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Apple
)
)
[7] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Orange
)
)
)
[2017-07-29] => Array
(
[9] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Orange
)
)
[11] => stdClass Object
(
[Job] => stdClass Object
(
[Name] => Plumb
)
)
)
)
I'm pretty sure I should be using array_multisort but can't quite get the desired results.
You must split the code if you want to order on object properties, use the usort function.
Where $arr is your array:
uksort($arr, 'dateCmp');
foreach($arr as &$sub){
usort($sub, 'propCmp');
}
function dateCmp($a, $b){
return (strtotime($a) < strtotime($b) ? -1 : 1);
}
function propCmp($a, $b){
return ($a->Job->Name < $b->Job->Name ? -1 : 1);
}
Please try below code,
$sorted_vals = array();
ksort($multiArrs);
foreach($multiArrs as $key => $value) { // $multiArrs = your data array
$columns = null;
foreach ($value as $index => $element) {
$columns[] = $element->Job;
}
$temp = $value;
array_multisort($columns, SORT_ASC, $temp);
$sorted_vals[$key] = $temp;
}
Im new to php and json. can you please suggest me on how to get the my desired output.
JSON File:
{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}
Desired Output
[
{
"minute":"1415772360",
"apple":"0",
"mango":"0",
"grapefruit":"0",
"melons":"12",
"peaches":"2",
"banana":"1”
},
{
"minute":"1415772420",
"apple:"0",
"mango":"0",
"grapefruit":"0",
"melons":"7",
"peaches":"1",
"banana":"1”
}
]
How can I do this in PHP?
I really appreciate your help. Thanks.
I would give json_decode a try. It won't get your desired output, but it will create an array from your JSON.
Documentation: http://php.net/manual/en/function.json-decode.php
My test:
$json = "{\"1415772360\":[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},
{\"melons\":\"12\"},{\"peaches\":\"2\"},{\"banana\":\"1\"}], \"1415772420\":
[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},{\"melons\":\"7\"},
{\"peaches\":\"1\"},{\"banana\":\"1\"}]}";
$new = json_decode($json);
print_r($new);
Output:
stdClass Object ( [1415772360] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 12 ) [4] => stdClass Object ( [peaches] => 2 )
[5] => stdClass Object ( [banana] => 1 ) ) [1415772420] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 7 ) [4] => stdClass Object ( [peaches] => 1 )
[5] => stdClass Object ( [banana] => 1 ) ) )
tyteen4a03 is correct that this just requires some looping to re-write the structure. This would be done as follows:
// Original JSON string
$json = '{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}';
// Convert JSON to array
$content = json_decode($json);
// Create new array container
$crate = array();
// Get minutes
foreach ($content AS $minute => $fruitbasket) {
$tmp = new stdClass;
$tmp->minutes = $minute;
// Get array of objects
foreach ($fruitbasket AS $fruits)
{
// Get object element and value
foreach ($fruits AS $key => $value)
{
// add to temporary object
$tmp->$key = $value;
}
}
// write to new array
$crate[] = $tmp;
}
print(json_encode($crate));
In my function im storing in $var1 a query from the database of posts. And im storing in $var2 a query from the database of images from the posts. (Each has a key post_id to connect them.)
$var1 will return something like this.
array (
[0] => stdClass Object
(
[post_id] => 210
[post_title] => title
)
[1] => stdClass Object
(
[post_id] => 212
[post_title] => title
)
)
and $var2 will return something like this.
array (
[0] => stdClass Object
(
[post_id] => 210
[post_meta_key] => image
[post_meta_value] => image_value
)
[1] => stdClass Object
(
[post_id] => 212
[post_meta_key] => flag
[post_meta_value] => flag_value
)
[2] => stdClass Object
(
[post_id] => 210
[post_meta_key] => image
[post_meta_value] => image_value
)
[3] => stdClass Object
(
[post_id] => 102
[post_meta_key] => image
[post_meta_value] => image_value
)
)
I would like to create a foreach from $var1 and if $var1[post_id] = $var2[post_id] than $var1 will be edited to something like this
array (
[0] => stdClass Object
(
[post_id] => 210
[post_title] => title
[image] => stdClass Object
(
[0] => image_value
[1] => image_value
)
)
[1] => stdClass Object
(
[post_id] => 212
[post_title] => title
)
)
How can i do this?
foreach ($var1 as &$post1)
{
foreach($var2 as $post2)
{
if ($post1->post_id == $post2->post_id)
{
$post1->image = (object)array(
$post2->post_meta_value
);
}
}
}
Better use arrays instead of objects here:
foreach ($var2 as $key2=>$var2){
if (!empty($var1[$key2])){
$var1[$key2]['image']->$var2;
}
}
You could cast arrays and objects back and forth with
$array = (array)$object;
$object = (object)$array;
This is what you want:
foreach ( $var1 as $v1 )
{
foreach ( $var2 as $v2 )
{
if ( $v1['post_id'] == $v2['post_id'] )
$v1['image'][] = $v2['post_meta_value'];
}
}