Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

php - Multidimensional Array to String

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...