php+print+r返回值,PHP: print_r - Manual

A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.

{$expecting=0;// 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'$lines=explode("\n",$output);$result=null;$topArray=null;$arrayStack= array();$matches=null;

while (!empty($lines) &&$result===null)

{$line=array_shift($lines);$trim=trim($line);

if ($trim=='Array')

{

if ($expecting==0)

{$topArray= array();$expecting=1;

}

else

{trigger_error("Unknown array.");

}

}

else if ($expecting==1&&$trim=='(')

{$expecting=2;

}

else if ($expecting==2&&preg_match('/^\[(.+?)\] \=\> (.+)$/',$trim,$matches))// array element{

list ($fullMatch,$key,$element) =$matches;

if (trim($element) =='Array')

{$topArray[$key] = array();$newTopArray=&$topArray[$key];$arrayStack[] =&$topArray;$topArray=&$newTopArray;$expecting=1;

}

else

{$topArray[$key] =$element;

}

}

else if ($expecting==2&&$trim==')')// end current array{

if (empty($arrayStack))

{$result=$topArray;

}

else// pop into parent array{// safe array pop$keys=array_keys($arrayStack);$lastKey=array_pop($keys);$temp=&$arrayStack[$lastKey];

unset($arrayStack[$lastKey]);$topArray=&$temp;

}

}// Added this to allow for multi line strings.else if (!empty($trim) &&$expecting==2)

{// Expecting close parent or element, but got just a string$topArray[$key] .="\n".$line;

}

else if (!empty($trim))

{$result=$line;

}

}$output=implode(n,$lines);

return$result;

}/**

* @param string $output : The output of a multiple print_r calls, separated by newlines

* @return mixed[] : parseable elements of $output

*/functionprint_r_reverse_multiple($output)

{$result= array();

while (($reverse=print_r_reverse($output)) !==NULL)

{$result[] =$reverse;

}

return$result;

}$output='

Array

(

[a] => apple

[b] => banana

[c] => Array

(

[0] => x

[1] => y

[2] => z

[3] => Array

(

[nest] => yes

[nest2] => Array

(

[nest] => some more

asffjaskkd

)

[nest3] => o rly?

)

)

)

some extra stuff

';var_dump(print_r_reverse($output),$output);?>

This should output

array(3) {

["a"]=>

string(5) "apple"

["b"]=>

string(6) "banana"

["c"]=>

array(4) {

[0]=>

string(1) "x"

[1]=>

string(1) "y"

[2]=>

string(1) "z"

[3]=>

array(3) {

["nest"]=>

string(3) "yes"

["nest2"]=>

array(1) {

["nest"]=>

string(40) "some more

asffjaskkd"

}

["nest3"]=>

string(6) "o rly?"

}

}

}

string(18) "nsome extra stuffn"

Added:

else if (!empty($trim) && $expecting == 2)

{

// Expecting close parent or element, but got just a string

$topArray[$key] .= "\n".$line;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值