How to convert an array to string with index

时间:2021-05-30 04:15:07

I would like to convert an Array like this:

我想像这样转换一个数组:

 array ( [1_1] => 1 [1_2] => 2 [1_3] => 3 [1_4] => 4 [1_5] => 5 )

to an string like this:

到这样的字符串:

"1_1-1/1_2-2/1_3-3/1_4-4/1_5-5"

how can I do it?

我该怎么做?

I need the Index and the values in my MySQL-Databse.

我需要索引和MySQL-Databse中的值。

I tryed implode() but this is the result:

我尝试了implode(),但这是结果:

1/2/3/4/5

thank you

3 个解决方案

#1


1  

$out = "";
foreach($arr as $k => $v) {
    $out .= "$k-$v/";
}
$out = substr($out, 0, -1); //this line will remove the extra '/'

#2


0  

PHP < 5.5

PHP <5.5

It's better to store all these values in an associative array and then implode them

最好将所有这些值存储在关联数组中,然后将它们内爆

$final = array();
foreach($array as $key => $val)
{
    $final[] = $key.'-'.$val;
}
$final = implode('/', $final);

PHP = 5.5

PHP = 5.5

You may want to use generators to yeld these values assuming they are regular: See: http://php.net/manual/en/language.generators.overview.php

假设它们是常规的,您可能希望使用生成器来大喊这些值:请参阅:http://php.net/manual/en/language.generators.overview.php

#3


0  

You can use http_build_query() to do that.

您可以使用http_build_query()来执行此操作。

http://www.php.net/http_build_query

Try:

     echo http_build_query($array, '', '/');

#1


1  

$out = "";
foreach($arr as $k => $v) {
    $out .= "$k-$v/";
}
$out = substr($out, 0, -1); //this line will remove the extra '/'

#2


0  

PHP < 5.5

PHP <5.5

It's better to store all these values in an associative array and then implode them

最好将所有这些值存储在关联数组中,然后将它们内爆

$final = array();
foreach($array as $key => $val)
{
    $final[] = $key.'-'.$val;
}
$final = implode('/', $final);

PHP = 5.5

PHP = 5.5

You may want to use generators to yeld these values assuming they are regular: See: http://php.net/manual/en/language.generators.overview.php

假设它们是常规的,您可能希望使用生成器来大喊这些值:请参阅:http://php.net/manual/en/language.generators.overview.php

#3


0  

You can use http_build_query() to do that.

您可以使用http_build_query()来执行此操作。

http://www.php.net/http_build_query

Try:

     echo http_build_query($array, '', '/');