如何将foreach循环输出为一个组合数组而不是单独的数组?

时间:2017-04-28 07:30:55

标签: php arrays json

我正在接收JSON输入,我需要通过脚本运行它并获取在新JSON数组中返回的值。然而,当我这样做时,它产生例如3个单独的阵列,而不是收到的一个大的阵列。示例:

Input:
[{
        "auth": "aa03e76d0a8bab11e08250000c29b481",
        "topic": "edafdff398fb22847a2f98a15ca3186e/1",
        "value": "1000"
},
{
        "auth": "aa03e76d0a8bab11e08250000c29b481",
        "topic": "edafdff398fb22847a2f98a15ca3186e/1",
        "value": "2000"
},
{
        "auth": "aa03e76d0a8bab11e08250000c29b481",
        "topic": "edafdff398fb22847a2f98a15ca3186e/2",
        "value": "3000"
}]

我通过以下脚本运行它:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with     hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special     chars.
}

//Get inputs from request
$data = array();
$data = json_decode(file_get_contents('php://input'), true);
$reply_array = array();

//Start looping through data
foreach($data as $mid => $input) {

    //Dig out the installation id and register
    $identify = explode('/',trim($input['topic'],'/'));
    $installation = preg_replace('/[^a-z0-9_]+/i','',array_shift($identify));
    $RegisterID = array_shift($identify)+0;

    // Extract the cleaning supplies needed to clean and validate the data
    $sql_get_detergent="SELECT ProfileID, Description, Lvl4, Register, BitNo, DataFormat, Units, LowAct, HighAct, Multiplier, FaultCondition, FaultText FROM DeviceProfiles WHERE RegisterID = '".$RegisterID."' ORDER BY RegisterID ASC";
    $result_get_detergent = mysqli_query($con,$sql_get_detergent);
    while($row_clean = mysqli_fetch_array($result_get_detergent)) {

        //Write out the reply
        $semantic = strtolower($row_clean['Lvl4']);
        $reply_array['topic'] = $installation."/".clean($semantic);
    }
    print_r(json_encode($reply_array));
}

输出不是我需要的 - 如此处所示它产生3个独立的阵列,而不是一个大的阵列。

Current output:
{"topic":"edafdff398fb22847a2f98a15ca3186e\/"}
{"topic":"edafdff398fb22847a2f98a15ca3186e\/"}
{"topic":"edafdff398fb22847a2f98a15ca3186e\/"}

Desired output:
[{
  "topic":"edafdff398fb22847a2f98a15ca3186e\/"
 },
 {
  "topic":"edafdff398fb22847a2f98a15ca3186e\/"
 },
 {
  "topic":"edafdff398fb22847a2f98a15ca3186e\/"
}]

我做错了什么?感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您正在foreach循环中打印每个结果,并在循环的下一次迭代中覆盖以前的结果。
当然,你会得到三个单一的结果。

更改您的代码:

$all_replies = array();
foreach($data as $mid => $input) {
    // [...]
    while($row_clean = mysqli_fetch_array($result_get_detergent)) {
        $reply_array = array();
        // Do you logic here - you can fill $reply_array as you want.
        $all_replies[] = $reply_array;
    }
}
print_r(json_encode($all_replies));

您也可以使用此方法,这是一个较小的更改:

$reply_array = array();
foreach($data as $mid => $input) {
    // [...]
    while($row_clean = mysqli_fetch_array($result_get_detergent)) {
        // [...]
        $reply_array[]['topic'] = $installation . "/" . clean($semantic);
    }
}
print_r(json_encode($reply_array));

这适用于您的示例案例,但在新作业中,您将无法在topic之外设置其他值。你必须这样做:

$reply_array = array();
foreach($data as $mid => $input) {
    // [...]
    while($row_clean = mysqli_fetch_array($result_get_detergent)) {
        // [...]
        $reply_array[] = array(
            'topic' => $installation . "/" . clean($semantic),
            'auth'  => $your_auth_value,
        );
    }
}
print_r(json_encode($reply_array));

我更喜欢带有额外变量的第一个解决方案,但另一个也适用。

答案 1 :(得分:0)

您的代码中存在一个小错误。

替换下面的代码:

$reply_array['topic'] = $installation."/".clean($semantic);

with:

$reply_array[]['topic'] = $installation."/".clean($semantic);