문제

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.

도움이 되었습니까?

해결책

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;

다른 팁

Already answered but here is a shorter version of this

$final_array =array();
foreach($arr as $key=>$val){
  $max = max(array_keys($val));
  $final_array[$key] = $val[$max]->ID ;
}

print_r($final_array);

Here $arr is your input array.

You need to do some compariosn in your inner for loop to know which one holds the max value. Here is an example :

$new_arr = array();
foreach($elements as $index => $value){
  $max = -1;
  $foreach($value as $obj){
    if($obj->id > $max)
      $max = $obj->id;
  }
  $new_arr [$index] = $max;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top