Search code examples
phparraysstdclass

PHP convert stdClass Object to string and reduce array with max value


I want to convert a stdClass object to string and reduce an array with the max value from the stdClass object.

This is my array:

Array
(

[135] => Array
    (
        [0] => stdClass Object
            (
                [ID] => 145
            )

        [1] => stdClass Object
            (
                [ID] => 138
            )

        [2] => stdClass Object
            (
                [ID] => 139
            )

    )

[140] => Array
    (
        [0] => stdClass Object
            (
                [ID] => 163
            )

        [1] => stdClass Object
            (
                [ID] => 155
            )
)

Basically it should look like this:

 Array
 (
 [135] => 139
 [140] => 164
 )

Is this possible? I've tried various foreach loops but i don't get it with the stdClass object...

My try so far:

 foreach($ids as $k => $v) {
   for($i = 0; $i < count($v); $i++) {
        $idss[$i] = array()$v;
    }
 }

That doesn't work.


Solution

  • This will solve your purpose. let me know if anything goes wrong.

    $ids[135][0]->ID = 145;
    $ids[135][1]->ID = 135;
    $ids[135][2]->ID = 155;
    $ids[140][0]->ID = 125;
    $ids[140][1]->ID = 135;
    $idss = array();
    foreach($ids as $k => $v) {
       for($i = 0; $i < count($v); $i++) {
            if(!@$idss[$k] || $v[$i]->ID > $idss[$k])
            {
                $idss[$k] = $v[$i]->ID;
            }
        }
     }
     echo "<Pre>";
     print_r($idss);
     die;