PHP - 将带有另一个数组的Key的值插入到特定位置的Array中

时间:2017-01-24 19:10:44

标签: php arrays json insert splice

我正在尝试根据从SQL Query接收的数据创建一个JSON对象作为数组。目前我编码的JSON是:

[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]

我想从另一个数组插入的值,这些值与上面JSON中每个数组的顺序相对应:(JSON)

 ["85.00000","50.00000","90.00000"]

所以JSON应该是这样的:

{"firstname":"Student","lastname":"1","grade":"85.00000"}

我当前的代码:

//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();

foreach($json_d->assignments[0]->grades as $gradeInfo) { 
    $grade[] = $gradeInfo->grade;
    $userid[] = $gradeInfo->userid;
}

//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

foreach($userid as $id) {
        $sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
        $result = mysqli_query($conn, $sql);

        if (mysqli_num_rows($result) > 0) {
        // output data of each row

            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
                $sqldata[] = $row;
            }

        } else {
            echo "ERROR!";
        }

}

$sqlr = json_encode($sqldata);
$grd = json_encode($grade);

echo $sqlr;
echo $grd;



mysqli_close($conn);

2 个答案:

答案 0 :(得分:0)

试试这段代码:

foreach($userid as $x => $id) {
    $sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
    // output data of each row

        while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
            $row['grade'] = $grade[$x];
            $sqldata[] = $row;
        }

    } else {
        echo "ERROR!";
    }
}

我添加了变量$x,并在$row['grade']数组

上添加了$grade相同的索引

答案 1 :(得分:0)

function set_column_values($arr, $column_name, $column_values) {
    $ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
        $arr_value[$column_name] = $col_value;
        return $arr_value;
    }, $arr, $column_values);

    return $ret_arr;
}

$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);

希望它有所帮助!