如何将两个不同的implode变量合并为一个数组?

时间:2014-11-14 07:54:11

标签: php arrays

以下是我的代码:

$id = $_GET['id'];
$qty = $_GET['qty'];
$product_id=$_GET['product_id'];

这是我在浏览器中收到的方式

http://example.com/shopping_cart.php?id=17,18&qty=4,5&product_id=3

$_SESSION['test'][]= array('product_id'=>$product_id,array('id'=>$id,'qty'=>$qty));

//print_r($_SESSION['test']);
foreach($_SESSION['test'] as $item=>$value)
{
    echo "Main Array ID=". $item;
    echo "<br/>";
    foreach($value as $v=>$v1)
    {
        if(is_array($v1))
        {
        echo "Sub Array ID=". $v;
        echo "<br/>";
        echo "size id=". $v1['id'];
        echo "<br/>";
        echo "Quantity=". $v1['qty'];
        echo "<br/>";
        }
    }
 }

输出:

Main Array ID=0
Sub Array ID=0
size id=12,13
Quantity=1,2
Main Array ID=1
Sub Array  ID=0
size id=17,18
Quantity=4,5

由于size_idquantity处于内幕,我的意思是他们有一个逗号&#39;,&#39;在价值之间。我需要将它们分解并使用foreach逐个显示。

我的意思是这样的:

$size_id1=explode(',',$v1['qty']);
foreach($size_id1 as $size_id2)
{
    echo $size_id2;
}

$qty1=explode(',',$v1['qty']);
foreach($qty1 as $qty2)
{
    echo $qty2;
}

我需要的是,我想显示匹配的size_idqty。例如,而不是显示:

size_id 1
size_id 2

Qty 1
Qty 2

应显示:

Size_id 1 Qty 1
Size_id 2 Qty 2

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

$ids = $_GET['id']
$qtys = $_GET['qty']
$product_id = $_GET['product_id'];

$tmp_result = array();
$ids = explode(',',$ids );
$i = 0;
foreach($ids as $id)
{          
      $tmp_result[$i]['id'] =  $id;
      $i++;
}

$i = 0;
$qtys =explode(',',$qtys );
foreach($qtys as $qty)
{          
      $tmp_result[$i]['qty'] =  $qty;
      $i++;
}    

$_SESSION['tmp_results'][$product_id] = $tmp_result;

答案 1 :(得分:0)

$temp_arr = array();
$id_str = '17,18';
$qty_str = '4,5';
foreach(array_combine(explode(',', $id_str), explode(',', $qty_str)) as $k => $v) {
    $temp_arr[]['id'] = $k;
    $temp_arr[]['qty'] = $v;
}

答案 2 :(得分:0)

来自数据库的2 implode fetch的差异

<?php  
 $select_tbl=mysql_query("select * from user_reg where uid='".           $_SESSION['user1']."'");
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->specialised;

$i=explode(",",$r);
$length = count($i);
for ($x=0; $x<$length; $x++)
{     
 echo $i[$x]; }
}?><tbody>
  <?php
mysql_connect("localhost","root","");
mysql_select_db("freelancer");
$query=mysql_query("select * from post_proj where status = 1 and payment =  '' ") or die(mysql_error());
$j = 1;
while($result=mysql_fetch_array($query))
{                   
if($result['uid'] == "")
{$d2 = $result['proj_skill'];
$pantry_food1 = explode(",",$d2);
$count_total1 = count($pantry_food1);
for ($counter=0; $counter<$count_total1; $counter++){
$line1 = each ($pantry_food1);
// echo $pantry_food1[$counter];
} $rrt = array_intersect($i,$pantry_food1);