【问题标题】:Combine JSON array into single value将 JSON 数组合并为单个值
【发布时间】:2014-04-22 11:56:32
【问题描述】:

我正在尝试连接几个 json 键值,以便我可以只返回一个包含所有数据的值。例如,在我的代码中,我想将地址 1、地址 2、地址 3 组合成地址。这可能吗。我尝试了各种使用 .= 的方法,但似乎没有任何效果。任何抬头将不胜感激。谢谢

$query = "SELECT * FROM company_com";
$from = 0; 
$to = 30;
$query .= " LIMIT ".$from.",".$to;

$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $customers[] = array(
        'Address1' => $row['address1_com'],
        'Address2' => $row['address2_com'],
        'Address3' => $row['address3_com']
      );
}

echo json_encode($customers);

【问题讨论】:

    标签: php json


    【解决方案1】:

    你可以像这样很好地重写..

    $customers = array(); $i=0; 
    $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $customers[$i]['Address1'] = $row['address1_com'];
        $customers[$i]['Address2'] = $row['address2_com'];
        $customers[$i]['Address3'] = $row['address3_com'];
        $i++;
    }
    echo json_encode($customers);
    

    所做的更改:

    • $customers 数组声明移到了while 之外
    • $i=0; 标志设置在 while 之外。
    • $customers 数组是二维的,您可以看到 $i 作为键传递。
    • 最后,$i 递增..

    EDIT :

    <?php
    $customers = array(); $i=0;
    $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $customers[$i]['Address'] = $row['address1_com']." ".$row['address2_com']." ".$row['address3_com'];
        $i++;
    }
    echo json_encode($customers);
    

    【讨论】:

    • 谢谢你。但是,我认为我需要返回类似:地址,以便我可以在 jquery 中用作数据字段。 var source = { datatype: "json", datafields: [ { name: 'Address', type: 'string'} ], url: 'data.php', cache: false };
    • 您想将所有三个地址合并到一个值中?
    • 非常感谢尚卡尔。非常感谢您的宝贵时间。
    • @user1532468,随时伴侣:)
    【解决方案2】:

    我不太明白你的问题。

    确保列名正确。 address1_com, address2_com, etc.

    在每次迭代中使用print_r($row); 测试代码。 print_r 显示数组的内容。

    另外,我建议您将每个地址组合成一个数组。比如……

    'Address' => array(
        $row['address1_com'],
        $row['address2_com'],
        $row['address3_com']
    )
    

    【讨论】:

    • 对不起,不太明白你的回答。所有字段均正确且 print_r 显示正确值。我只需要组合成一个名称,即;作为数据字段包含在 jquery 中的地址。谢谢
    猜你喜欢
    • 2015-12-13
    • 2021-11-09
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2019-08-30
    • 2015-09-28
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多