将动态变量添加到数组中

时间:2015-05-07 14:41:16

标签: php arrays

public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
    if (ModelState.IsValid)
    {
        using (var northwind = new NorthwindEntities())
        {
            // Create a new Product entity and set its properties from the posted ProductViewModel
            var entity = new Product
            {
                ProductName = product.ProductName,
                UnitsInStock = product.UnitsInStock
            };
            // Add the entity
            northwind.Products.Add(entity);
            // Insert the entity in the database
            northwind.SaveChanges();
            // Get the ProductID generated by the database
            product.ProductID = entity.ProductID;
        }
    }
    // Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
    return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}

我正在尝试使用以下代码改进上述代码:

    foreach ( $tbl_one_data as $row_ ) {
        $id = ( int ) $row_ [0];
        $time = mysql_real_escape_string ( $row_ [1] );
        $callid = mysql_real_escape_string ( $row_ [2] );
        $queuename = mysql_real_escape_string ( $row_ [3] );

        $arrayValues [] = "($id, '$time','$callid','$queuename',";
    }
}

我的问题是如何逐步添加创建到数组中的动态变量来实现这样的事情: $b = 0; foreach ( $tbl_one_data as $row_ ) { if ($b < count ( $row_ )) { ${"var" . $b} = mysql_escape_string ( $row_ [$b] ); $b ++; } } ??

$arrayValues [] = "('$var0','$var1','$var2','$var3'";似乎与我的第一个代码段没有相同的效果。

2 个答案:

答案 0 :(得分:1)

我相信这就是你所要求的:

foreach ( $tbl_one_data as $row_ ) {
    $arrayValues [] = "('" . implode("','", $row_) . ",";
}

$ row_中的所有元素通过implode()使用逗号和单引号作为“粘合剂”连接成一个字符串。

如果这没有帮助或不是您想要的,请发表评论,我们会尝试获得更好的反馈。

答案 1 :(得分:0)

您只需使用以下代码即可制作:

Num [a]