0

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
  • There is no best practice for something mundane like this, once you know how to manipulate arrays, it just comes with practice to do it in less code. Commented Jul 10, 2017 at 9:50
  • Is there any built-in function in php or recursive way? Commented Jul 10, 2017 at 10:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

nice , but there is a problem , my final result is look this : """string A string B """ what is your suggestion for convert to "string A string B"
So you have quotes in your input array?
0

There's two arrays nested in OP's example. So you'll need two loops if you don't pop off the top.

$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.