9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPのラムダで再帰

Posted at

方法

  1. ラムダ定義時に use でスコープに変数を追加することが出来る
  2. ラムダ自身の参照を追加してやる


例えば SimpleXML を使用して配列に変換する場合

convert_xml_to_array.php
<?php  
// 配列作成無名関数
$fun = function ($simplexml, $out=array()) use (&$fun) {
    foreach ( (array) $simplexml as $index => $node ) { 
        if ( is_object($node) || is_array($node) ) { 
            $out[$index] = $fun($node);
        }   
        else {
            $out[$index] = $node;
        }   
    }   
    return $out;
};

$simplexml = simplexml_load_string($str);
var_dump( $fun($simplexml) );

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?