【问题标题】:Array not populating correctly数组未正确填充
【发布时间】:2010-07-05 17:03:12
【问题描述】:

我正在使用以下代码来填充数组:

$number = count ($quantitys);
    $count = "0";
    while ($count < $number) {
        $ref[$count] =  postcodeUnknown ($prefix, $postcodes[$count]);  
        $count = $count +1;
    }

postcodeUnknown 返回 mysql 查询的第一行,使用表前缀和名为 postcodes 的数组中的元素。 $postcodes 包含的字符串应该每次通过循环返回不同的行。

我希望创建一个类似于以下内容的数组:

Array ([0] => 
       Array ([0] => some data [1] => more data) 
[1] => 
       Array ([0] => second row [1] => even more...)
)

但事实并非如此。相反,它会一遍又一遍地创建一个包含第一个结果的奇怪数组,直到满足条件,例如:

print_r($ref)的简化结果;

Array (
   [0] => Array ([0] => some data [1] => more data)
) 
Array(
   [0] => Array (
        [0] => the first arrays content... 
        [1] => ...repeated over again until the loop ends
     )
)

我不知道为什么。有谁比我更了解。

【问题讨论】:

  • 我只是在格式化你的问题并意识到第二个数组看起来不正确......你能用正确的输出更新吗?谢谢
  • 这就是问题的重点。格式不正确

标签: php arrays count loops


【解决方案1】:

试试

$number = count ($quantitys);
$count = "0";
while ($count < $number) {
    $ref1[$count] =  postcodeUnknown ($prefix, $postcodes[$count]);
    $ref2[] =  postcodeUnknown ($prefix, $postcodes[$count]);
    $ref3[$count][] =  postcodeUnknown ($prefix, $postcodes[$count]);
    $count = $count +1;
}


echo "<pre>";
print_r($ref1);
print_r($ref2);
print_r($ref3);
echo "</pre>";

试试看是否有任何一个得到你正在寻找的输出。

【讨论】:

  • 这些都不起作用。我将尝试删除 unknownPostcode 函数并检查它是否有错误。
  • 已修复。我试过你的建议 - 没有运气。但是,我随后尝试将计数 ($quantitys) 更改为计数 ($postcodes)。这不应该影响任何事情,因为它们始终是相同长度的数组,无论如何它都有效。
  • 好的,如果 unknownPostcode 返回一个数组,那么 $ref[$count] = unknownPostcode() 应该可以工作。
【解决方案2】:

呃,给 postcodeUnknown 添加一个 print 并检查它是否真的传递了不同的邮政编码或相同的东西?

function postcodeUnkown($a,$b){
    echo var_dump($a).var_dump($b);
    //the rest
}

另外,为什么有两个不同的变量? ($quantitys 和 $postcodes)。

另外,您可能想用 for 替换 while 循环:

for($i=0;$i<$number;$i++){
    $ref[$i] =  postcodeUnknown ($prefix, $postcodes[$i]);        
}

【讨论】:

  • 这并没有修复格式错误的数组问题。据我所知,问题的根源与 $count 迭代有关。虽然 postcodeUnknown 被调用了适当的次数,但它似乎使用 $postcodes[0] 调用,而不管循环运行了多少次。顺便说一句,我正在使用 MAMP 进行开发。
【解决方案3】:

你的变量计数不应该是一个字符串,试试这个

$number = count ($quantitys);
    $count = 0;
    while ($count < $number) {
        $ref[$count] =  postcodeUnknown ($prefix, $postcodes[$count]);  
        $count = $count +1;
    }

【讨论】:

  • 这不会是问题,因为 PHP 仍然会通过将字符串转换为 int 来增加字符串
  • 检查以确保 - 没有变化。
猜你喜欢
  • 2012-03-19
  • 2015-09-22
  • 2022-10-01
  • 2021-07-27
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
相关资源
最近更新 更多