【问题标题】:How to convert stdClass object in to refrence array? (PHP)如何将 stdClass 对象转换为参考数组? (PHP)
【发布时间】:2014-07-10 17:42:37
【问题描述】:

我有变量 $related 女巫是 stdCalss 对象,我想用一个 foreach 循环将它转换为 reffrence 数组。

对象$relatedVar_dump

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代码:

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

希望的输出:

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

【问题讨论】:

    标签: php arrays object reference


    【解决方案1】:

    构建一个临时数组并内爆它:

    foreach($related AS $r) {
        $temp[$r->id_product][] = $r->related;
        $rels[$r->id_product]   = implode(', ', $temp[$r->id_product]);
    }
    print_r($rels);
    

    【讨论】:

      【解决方案2】:
      $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);
      

      【讨论】:

        【解决方案3】:

        试试,

        $rels = array();
        foreach($related as $r){
        
           $rels[$r->id_product] .= $r->related.', ';
        
        }
        
        array_walk_recursive($related, function(&$item){
            $item = rtrim($item,', ');
        });
        

        来自 PHP 文档:http://php.net/manual/en/language.types.type-juggling.php

        【讨论】:

          猜你喜欢
          • 2011-11-08
          • 1970-01-01
          • 2013-10-29
          • 2018-08-09
          • 1970-01-01
          • 2016-03-29
          • 2020-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多