假设我有一个这样的数组,它可能是多维的,所以我确实需要使这个循环递归。
我想我已经很接近了,但看不出我错在哪里了。
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b = $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
预期结果应该是:
"rigging, animation, modeling"
我得到的只是"建模",
在您的代码中,您需要编写
$b .= $this->_replace_amp($value); // note the period
如果没有句点,则每次脚本找到新数组时都会启动$b
,但您希望将结果附加到$b
。
除此之外,还有一个适用于多维数组的内爆函数:
/**
* Recursively implodes an array with optional key inclusion
*
* Example of $include_keys output: key, value, key, value, key, value
*
* @access public
* @param array $array multi-dimensional array to recursively implode
* @param string $glue value that glues elements together
* @param bool $include_keys include keys before their values
* @param bool $trim_all trim ALL whitespace from string
* @return string imploded array
*/
function recursive_implode(array $array, $glue = ',', $include_keys = false, $trim_all = true)
{
$glued_string = '';
// Recursively iterates array and adds key/value to glued string
array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glued_string)
{
$include_keys and $glued_string .= $key.$glue;
$glued_string .= $value.$glue;
});
// Removes last $glue from string
strlen($glue) > 0 and $glued_string = substr($glued_string, 0, -strlen($glue));
// Trim ALL whitespace
$trim_all and $glued_string = preg_replace("/('s)/ixsm", '', $glued_string);
return (string) $glued_string;
}
来源:https://gist.github.com/jimmygle/2564610
我认为json_encode(your_php_array)或serialize()函数对您有帮助。
您想要使用函数内爆()。没有必要重新发明轮子。
<?php
$arr = ['one', 'two', 'three'];
echo implode(',', $arr); // one, two, three
$b=$this->_replace_amp($value);将此行更改为$b.=$this->_replace_amp($value);这个答案根据你的编码
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b .= $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
使用已使用的implode(',',$array);
的最佳方法