Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to convert a multidimensional array into a string with a particular format.

function convert_multi_array($array) {
    foreach($array as $value) {
        if(count($value) > 1) {
            $array = implode("~", $value);
        }
        $array = implode("&", $value);
    }
    print_r($array);
}
$arr = array(array("blue", "red", "green"), array("one", "three", "twenty"));
convert_multi_array($arr);

Should Output: blue~red~green&one~three~twenty ... and so on for more sub-arrays.

Let me just say that I have not been able to produce any code that is remotely close to the results I want. After two hours, this is pretty much the best I can get. I don't know why the implodes are acting differently than they usually do for strings or maybe I'm just not looking at this right. Are you able to use implode for arrays values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are overwriting $array, which contains the original array. But in a foreach a copy of $array is being worked on, so you are basically just assigning a new variable.

What you should do is iterate through the child arrays and "convert" them to strings, then implode the result.

function convert_multi_array($array) {
  $out = implode("&",array_map(function($a) {return implode("~",$a);},$array));
  print_r($out);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...