我正在创建一个可以帮助我将字符串转换为数组的函数,但是当函数总是将第一个字符添加到数组时,这很奇怪。首先感谢,这是我在函数中使用的代码:
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
//var_dump($explodedString);
$takeArray = array();
$counti = 0;
foreach($explodedString as $exploded){
$secondExp = explode(':', $exploded);
var_dump($secondExp);
if(isset($takeArray[$secondExp[0]])){
$takeArray[$secondExp[0]][$counti] = $secondExp[1];
}else{
$takeArray[$secondExp[0]] = $secondExp[1];
}
$counti++;
}
var_dump($takeArray);
这是此代码的当前输出:
array (size=9)
0 => string '009987' (length=6)
1 => string '12312' (length=5)
2 => string '45231' (length=5)
3 => string '00981' (length=5)
4 => string '11253 605181' (length=12)
5 => string '9801' (length=4)
6 => string '1092 41' (length=16)
7 => string '450' (length=3)
8 => string '34' (length=2)
查看第4行,你会看到字符串:'605181',这个字符串来自每个值的第一个字符属于4.但我需要一个像这样的输出数组:
[0] => {'009987'},
....
[4] => { '11253', '62341', ...., },
....
请帮帮我。
答案 0 :(得分:2)
我不确定你为什么需要$counti
。您需要做的就是初始化$takeArray[$n]
(如果它不存在),并将新值推送给它。像这样:
if(!isset($takeArray[$secondExp[0]])) {
// Initialize the array
$takeArray[$secondExp[0]] = array();
}
// Push the new value to the array
$takeArray[$secondExp[0]][] = $secondExp[1];
答案 1 :(得分:1)
您只需要执行以下操作:
How to Use Tables
答案 2 :(得分:0)
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
$takeArray = array();
foreach($explodedString as $exploded)
{
$secondExp = explode(':', $exploded);
$takeArray[$secondExp[0]][] = $secondExp[1];
}
var_dump($takeArray);