dongnanbi4942
2014-07-28 12:25
浏览 41
已采纳

将变量循环到Array中,然后将其编码为1 JSON

I had been searching for a while, and I can't seem to find a solution for my problem, so I created an account.

My situation is as below.

  1. I am doing a for loop upload image form.

  2. Every time it loops, it will have 1 $Listingid.photo

  3. I would like to add all the $Listingid.photo into an array, then package it into 1 JSON. and echo it.

And I am not very sure how to approach it. At the moment it is creating 1 JSON response per loop.

Only the last two lines of my code really matters to the problem.

My code:

<?php
ini_set('display_errors', 1); error_reporting(E_ALL);

ob_start();
session_start();
include 'connect.php';

$Listingid =($_POST['listingid']);

if(isset($_FILES['file'])) {
    $_FILES["file"]["name"] = preg_replace('/\s+/', '', $_FILES["file"]["name"]);
    for($i=0;$i<count($_FILES["file"]["name"]);$i++)
    {

        $photo=$_FILES["file"]["name"][$i];
        $newname=$Listingid.$photo;
        move_uploaded_file($_FILES["file"]["tmp_name"][$i], "photo/$Listingid$photo");

        mysqli_query($con,"INSERT INTO listingpic (pic,listingid) VALUES ('$newname','$Listingid');") or die(mysqli_error($con));

        $arr = array('picname' => $Listingid.$photo);
        echo json_encode($arr);
    }
}

图片转代码服务由CSDN问答提供 功能建议

我一直在搜索,我似乎无法找到解决问题的方法,所以我 创建了一个帐户。

我的情况如下。

  1. 我正在进行for循环上传图片表格。

  2. 每次循环时, 它将有1 $ Listingid.photo

  3. 我想将所有 $ Listingid.photo 添加到 一个数组,然后将其打包成1个JSON。 并回应它。

    我不太确定如何处理它。 目前它正在为每个循环创建1个JSON响应。

    我的代码的最后两行对问题非常重要。

    我的代码:

      &lt;?php 
    ini_set('display_errors',1);  error_reporting(E_ALL); 
     
    ob_start(); 
    session_start(); 
    include'connect.php'; 
     
     $ Listingid =($ _ POST ['listingid']); 
     
    if(isset($  _FILES ['file'])){
     $ _FILES [“file”] [“name”] = preg_replace('/ \ s + /','',$ _FILES [“file”] [“name”]);  
     for($ i = 0; $ i&lt; count($ _ FILES [“file”] [“name”]); $ i ++)
     {
     
     $ photo = $ _ FILES [“file”] [“  name“] [$ i]; 
     $ newname = $ Listingid。$ photo; 
     move_uploaded_file($ _ FILES [”file“] [”tmp_name“] [$ i],”photo / $ Listingid $ photo“);  
     
     mysqli_query($ con,“INSERT INTO listingpic(pic,listingid)VALUES('$ newname','$ Listingid');”)或die(mysqli_error($ con)); 
     
     $ arr =  array('picname'=&gt; $ Listingid。$ photo); 
     echo json_encode($ arr); 
    } 
    } 
       
     
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douju1997 2014-07-28 12:29
    最佳回答
    $arr[]=array('picname' => $Listingid.$photo);
    

    then move the echo json_encode out of the loop

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题