2017-04-18 71 views
4

我已經看過這裏的幾個答案,但似乎並沒有利用這種方法?使用array_walk_recursive()爲stdClass對象

我有一個項目的數組,項目是對象。該對象可以有一個「兒童」和「兒童」的關鍵是一個對象數組等。

有沒有辦法實現這一點?

實施例:

Array 
    (
     [1] => stdClass Object 
      (
       [id] => 1 
       [name] => Steve King 
       [image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg 
       [parent] => 0 
       [children] => Array 
        (
        ) 

      ) 

     [2] => stdClass Object 
      (
       [id] => 2 
       [name] => Eden Hall 
       [image] => upload/shop/064f60a98deba612e437ac549f1dc05d.jpg 
       [parent] => 0 
       [children] =>Array 
        (
         [1] => stdClass Object 
          (
           [id] => 1 
           [name] => Steve King 
           [image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg 
           [parent] => 0 
           [children] => Array 
            (
           ) 

        ) 
      ) 
     [3] => stdClass Object 
      (
       [id] => 3 
       [name] => Paula Johnson 
       [image] => upload/shop/1492a323090afbad07c35cf93fe6bdda.jpg 
       [parent] => 0 
       [children] => Array 
        (
        ) 

      ) 

     [4] => stdClass Object 
      (
       [id] => 4 
       [name] => Ethan Watson 
       [image] => upload/shop/677c720333af33bc58d0684d79918e03.jpg 
       [parent] => 0 
       [children] => Array 
        (
        ) 

      ) 

     [5] => stdClass Object 
      (
       [id] => 5 
       [name] => Abigail Adams 
       [image] => upload/shop/da1734277322fc3b2e84a9ddbcc2e2f1.jpg 
       [parent] => 0 
       [children] => Array 
        (
        ) 

      ) 

回答

3

分配對象的數組$array下。

解決方案1:json_encode對象的數組,使之成爲json然後轉換一個jsonassociative array。過陣列迭代並鍵入鑄造每個object作爲array

$result=json_decode(json_encode($array),true); 
array_walk_recursive($result, function($value,$key){ 
    print_r($value); 
    print_r($key); 
}); 

溶液2。

array_walk($array,function(&$value,$key){ 
    $value=(array) $value; 
}); 
array_walk_recursive($array, function($value,$key){ 
    print_r($value); 
    print_r($key); 
}); 
+0

謝謝。我想這是不可能循環,同時保持它們作爲對象呢? –

+0

@RyanHipkiss array_walk_recursive只適用於數組而不是對象。 –

+0

@RyanHipkiss歡迎... :) –

2

您總是可以爲特定的數據結構實現自定義遞歸迭代器。它可以是更靈活的解決方案。例如:

class MyIterator extends \IteratorIterator implements 
\RecursiveIterator 
{ 
    public function hasChildren() 
    { 
     $current = $this->current(); 

     if (is_array($current) and $this->key() === 'children') { 
      return true; 
     } 

     return is_object($current); 
    } 

    public function getChildren() 
    { 
     /* $current is array (for key 'children') or \stdClass obj*/ 

     $current = $this->current(); 

     return new MyIterator(new \ArrayObject($current)); 
    } 
} 

$rii = new \RecursiveIteratorIterator(new MyIterator(new 
\ArrayObject($data))); 

foreach ($rii as $key => $value) { 
    print_r($key); 
    print_r($value); 
}