1

I have variable $related witch is stdCalss object and i want to convert it with one foreach loop in to reffrence array.

Var_dump of Object $related:

array (size=19)
  0 => 
    object(stdClass)[20]
      public 'id_product' => string '1568' (length=4)
      public 'related' => string '1567' (length=4)
  1 => 
    object(stdClass)[21]
      public 'id_product' => string '1568' (length=4)
      public 'related' => string '1562' (length=4)
  2 => 
    object(stdClass)[22]
      public 'id_product' => string '1568' (length=4)
      public 'related' => string '1564' (length=4)
  3 => 
    object(stdClass)[23]
      public 'id_product' => string '1568' (length=4)
      public 'related' => string '1410' (length=4)
  4 => 
    object(stdClass)[24]
      public 'id_product' => string '111' (length=3)
      public 'related' => string '77' (length=2)
  5 => 
    object(stdClass)[25]
      public 'id_product' => string '111' (length=3)
      public 'related' => string '1610' (length=4)

Php code:

     foreach ($related AS $r){
     ????
     }
     var_dump($rels);

Wished Output:

    $rels = array(
           '1568'=>'1567, 1562, 1564, 1410',
           '111'=>'77,1610'
            );

3 Answers 3

1

Build a temporary array and implode it:

foreach($related AS $r) {
    $temp[$r->id_product][] = $r->related;
    $rels[$r->id_product]   = implode(', ', $temp[$r->id_product]);
}
print_r($rels);
Sign up to request clarification or add additional context in comments.

Comments

1
$rels = array ();
foreach ($related as $r){
     $rels[$r->id_product] .= $r->related . ","; // put all of them with respective key together
}
$rels = array_map(
    function ($a) {
        $a = preg_replace('~,(?!.*,)~', '', $a);
        return $a;
    }
,$rels); // remove last commas
var_dump($rels);

Comments

1

Try,

$rels = array();
foreach($related as $r){

   $rels[$r->id_product] .= $r->related.', ';

}

array_walk_recursive($related, function(&$item){
    $item = rtrim($item,', ');
});

From the PHP docs: http://php.net/manual/en/language.types.type-juggling.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.