我想以这种方式连接一些字符串:
"string A"
"string B"
my expectation result : "string A \n string B"
这里我的初始数组看起来像这样:
array:1 [
0 => array:2 [
"foo" => array:1 [
0 => "string A"
]
"bar" => array:1 [
0 => "string B"
]
]
]
这样做的最佳做法是什么?
答案 0 :(得分:2)
似乎你可以使用相当通用的数组展平函数:
function get_flattened_values($arr, $glue = "\n"){
$result = array();
// For each array item in this level of the array
foreach($arr as $item){
// If it's the element is an array, recurs and push the result
if(is_array($item)){
$result[] = get_flattened_values($item);
// Else, if it's a string, just push the string
} else if (is_string($item)){
$result[] = $item;
}
}
// Join our result together
return implode($glue, $result);
}
的示例
答案 1 :(得分:0)
在OP的示例中嵌套了两个数组。所以如果你不从顶部弹出,你将需要两个循环。
$array1 = array("foo" => "something");
$array2 = array("bar" => "somethingelse");
$result = array_merge($array1, $array2);
//your array here:
$mytest = (array($result));
foreach ($mytest as $key => $value)
{
foreach($value as $innerItem => $innerValue){
$str .= ($innerValue);
}
}
echo($str);