数组从1开始而不是从0开始

时间:2015-06-18 02:20:24

标签: php arrays

我有一个像这样的数组:

Array ( [Pembangunan] => 100 [Komputer] => 200 [Sekolah] => 300 [Osis] => 400 ) 

之后,我把它调成foreach以插入数据库,但我的结果总是这样:

INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Komputer', '100')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Sekolah', '100')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Osis', '100')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('', '100')

关键" Pembangunan"从未打电话过有谁知道为什么?看起来索引始终从1

开始

这是我的代码:

$item = $_POST['mexpense'];
$namexp = $_POST['namexp'];
$newarr = array();
$arr = array();
foreach ($namexp as $val)
{
    array_push($newarr, $val);
}   

foreach ($item as $val2)
{
    array_push($arr, $val2);
}

$arres = array_combine($newarr, $arr);
print_r($arres);
echo "<br />";
asort($arres);
foreach ($arres as $value)
{
    $qq = "INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('".key($arres)."', '".remdot($value)."')";
    echo $qq."<br />";
    //mysqli_query($conn,$qq);
    next($arres);
}

3 个答案:

答案 0 :(得分:3)

  • next($arres)循环
  • 中有foreach
  • 使用foreach ($arres as $key => $value)迭代数组,可以轻松访问$key$value

更新代码

foreach ($arres as $key => $value)
{
    $qq = "INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('".$key."', '".remdot($value)."')";
    echo $qq."<br />";
    //mysqli_query($conn,$qq);

    // REMOVE 
    //next($arres);
}

答案 1 :(得分:1)

您可以访问以下示例中的密钥,

foreach ($array as $key => $value)

答案 2 :(得分:0)

试试这个,我认为这个逻辑会帮助你

$cobaini =Array ( 'Pembangunan' => 100 ,'Komputer' => 200 ,'Sekolah' => 300 ,'Osis' => 400 ); 

foreach ($cobaini as $key => $nilai) {
    echo "INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('".$key."','".$nilai."')";
    echo "<br>";
}

结果是

INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Pembangunan','100')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Komputer','200')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Sekolah','300')
INSERT INTO m_student_payment(sp_biaya, sp_jmlbiaya) VALUES ('Osis','400')