I want to concatenate some string in this way:
我想以这种方式连接一些字符串:
"string A"
"string B"
my expectation result : "string A \n string B"
And Here my initial array look like this :
在这里,我的初始数组看起来像这样:
array:1 [
0 => array:2 [
"foo" => array:1 [
0 => "string A"
]
"bar" => array:1 [
0 => "string B"
]
]
]
What is the best practice for doing this?
这样做的最佳做法是什么?
2 个解决方案
#1
2
Seems as though you could use a fairly generic array-flattening function for this:
好像你可以使用相当通用的数组展平函数:
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);
}
Example at eval.in
eval.in上的示例
#2
0
There's two arrays nested in OP's example. So you'll need two loops if you don't pop off the top.
在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);
#1
2
Seems as though you could use a fairly generic array-flattening function for this:
好像你可以使用相当通用的数组展平函数:
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);
}
Example at eval.in
eval.in上的示例
#2
0
There's two arrays nested in OP's example. So you'll need two loops if you don't pop off the top.
在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);