douxian9706
2012-11-19 07:00 阅读 41

在foreach中传递3个数组

In java code i have this

ArrayList<NameValuePair> al = new ArrayList<NameValuePair>();

for (int i = 0; i < alitems.size(); i++) {

    al.add(new BasicNameValuePair("items[]", alitems.get(i)));
    al.add(new BasicNameValuePair("qty[]", alnoof.get(i)));
    al.add(new BasicNameValuePair("price[]", alprice.get(i)));
}

Note: here alitems, alnoof, alprice are ArrayLists

php code

foreach (array_combine($_POST['items'], $_POST['qty']) as $val => $no) {

   $v = mysql_real_escape_string($val);
   $va = mysql_real_escape_string($no);
}

now i am able to get 2 array values of $v and $va but I am not able to get the price arraylist. How to do it?

suppose $_POST['items']={pencil,pen,watch}
        $_POST['qty']={2,3,4}
        $_POST['price']={20,30,40}

i need to insert values in database as :

pencil,2,20   pen,3,30   watch,4,40

Kindly help me on how to achieve this.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duannaoye0732 duannaoye0732 2012-11-19 07:03

    PHP also has for loop

    $_POST['items'] = ["pencil","pen","watch"];
    $_POST['qty'] = [2,3,4];
    $_POST['price'] = [20,30,40];
    
    for($i = 0; $i < count($_POST['items']); $i ++) {
        echo $_POST['items'][$i], " ", $_POST['qty'][$i], " ", $_POST['price'][$i], PHP_EOL;
    }
    

    Or

    foreach ( array_map(null, $_POST['items'], $_POST['qty'], $_POST['price']) as $var ) {
        list($item, $qty, $price) = $var;
        echo $item, " ", $qty, " ", $price, PHP_EOL;
    }
    

    Please not that [] is only supported in PHP >= 5.4 other whise you have to use array()

    点赞 评论 复制链接分享

相关推荐