php如何循环数组的值

时间:2013-07-13 12:54:31

标签: php arrays

我有以下php代码:

$range=range(1,$count);
$value=implode(",",$range);
$query1="SELECT DISTINCT numar_factura FROM creeazafactura WHERE numar_factura IN ($value)";
$result1=mysql_query($query1);

while ($rowx = mysql_fetch_assoc($result1)) {
    $getvalue[]=$rowx['numar_factura'];
}
$missingvalue = array_diff($range,$getvalue);

print_r($range);
print_r($getvalue);
print_r($missingvalue);

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Array
(
    [0] => 1
    [1] => 2
)

Array
(
    [2] => 3
)

我想弄清楚的是,如何做到以下一行

printf("WARNING: The invoice $missing[2] is missing.");

总能奏效。为什么我总是这么说?因为现在id删除了第3张发票,但如果我删除了第二张发票,我将有数组[1]输出$ missing

答案是制作一个循环,以便我在printf中有$ missing [$ loop],

循环搜索一个或两个发票已删除..并输出1或2行。

很容易说,很难做到,当你是初学者并且你想为使用excel的朋友做一个简单的发票系统时:)

如果您可以提供一些示例或某些文档的链接,您可以帮我一个忙。谢谢

2 个答案:

答案 0 :(得分:3)

这样做:

foreach($missingvalue as $key => $value)
{
    printf('WARNING: The invoice '.$value.' is missing.');
}

答案 1 :(得分:0)

目的是获取缺少发票的ID。 试试这个:

// here's your missing invoice array
$missingvalue = array_diff($range,$getvalue);
// get keys of it
$missingvalue_keys = array_keys($missingvalue);
// and now get the value from $missingvalue by key from $missingvalue_keys
printf('WARNING: The invoice ' . $missing[$missingvalue_keys[0]] . ' is missing.');

// if you have multiple values in $missingvalue than you dont need keys
foreach ($missingvalue as $value)
    printf('WARNING: The invoice ' . $value . ' is missing.');
// or with implode
printf('WARNING: The invoices ' . implode(',', $missingvalue) 
        . ' are missing.');