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

时间:2022-03-17 21:18:09

I'm receiving a JSON input, and I need to run it through a script and get the values returned in a new JSON array. However when I do so, it yields eg 3 separate arrays, not one big one as it received. Example:

我正在接收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"
}]

I run it through the following script:

我通过以下脚本运行它:

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));
}

Output is not what I need - as seen here it yields 3 separate arrays, not one big one.

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

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

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

What am I doing wrong? Appreciate your help!

我究竟做错了什么?感谢你的帮助!

2 个解决方案

#1


2  

You are printing each result in the foreach loop, and in the next iteration of the loop you overwrite the previous result.
Of course you get three single results that way.

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

Change your code like this:

像这样更改你的代码:

$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));

You could also use this approach, which is a smaller change:

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

$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));

That will work for your example case, but you'll not be able to set another value apart from topic in a new assignment. You'd have to do it this way:

这将适用于您的示例案例,但您将无法在新分配中设置除主题之外的其他值。你必须这样做:

$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));

I prefer the first solution with an extra variable, but the other one works, too.

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

#2


0  

There is a small mistake in your code.

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

Replace below code :

替换下面的代码:

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

with :

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

#1


2  

You are printing each result in the foreach loop, and in the next iteration of the loop you overwrite the previous result.
Of course you get three single results that way.

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

Change your code like this:

像这样更改你的代码:

$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));

You could also use this approach, which is a smaller change:

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

$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));

That will work for your example case, but you'll not be able to set another value apart from topic in a new assignment. You'd have to do it this way:

这将适用于您的示例案例,但您将无法在新分配中设置除主题之外的其他值。你必须这样做:

$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));

I prefer the first solution with an extra variable, but the other one works, too.

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

#2


0  

There is a small mistake in your code.

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

Replace below code :

替换下面的代码:

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

with :

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