解析字典对象并通过PHP创建MySQL表

时间:2014-05-27 01:17:06

标签: php mysql parsing dictionary

目前,我的PHP脚本中有这个字典对象,通过我的iOS应用程序发布到我的PHP实现服务器:

{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}

现在我需要根据数据创建一个MySQL表...

这是我尝试解析数据,但我得到的只是对象,而不是键......

foreach( $text as $stuff ) {
    if( is_array( $stuff ) ) {
        echo json_encode($stuff);
        foreach( $stuff as $thing ) {
            echo json_encode($thing);
        }
    } else {
        echo json_encode($stuff);
    }
}

结果是...... "save""GameScore""0""SeanPlott""1337"

我打算将其作为查询

$result = query("INSERT INTO '%s'('%s', '%s', '%s', '%s') 
                    VALUES('%s','%s','%s','%s')", $classname, $key1, $key2, $key3, $key4, 
                                                    $object1, $object2, $$object3, $object4);

但是查询应该是动态的,因为字典对象可以有1个或多个键/对象......

所以我想我需要实现一个解析for循环,在数组中生成查询并输出一个字符串作为查询......

任何人对如何修复我的解析器都有任何想法?

编辑:继承我的查询函数来处理MYSQL

function query() {
    global $link;
    $debug = false; 
    $args = func_get_args();
    $sql = array_shift($args);

    for ($i = 0; $i < count($args); $i++) {
        $args[$i] = urldecode($args[$i]);
        $args[$i] = mysqli_real_escape_string($link, $args[$i]);
    }

    $sql = vsprintf($sql, $args);

    if ($debug) print $sql;

    $result = mysqli_query($link, $sql);

    if (mysqli_errno($link) == 0 && $result) {  
        $rows = array();

        if ($result !== true)
            while ($d = mysqli_fetch_assoc($result)) 
                array_push($rows,$d);

        return array('result' => $rows);

    } else {
        return array('error' => 'Database error');
    }
}
编辑:我花了一些时间和很多帮助,但我完成了它...它处理值中空格的情况,并在键周围添加“''字符,如果相应的值包含空格...

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"Sean Plott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_slice(array_keys($data), 2);
array_shift($data);
$table_title = array_shift($data);

$values = array();
$num = 0;
foreach($data as $key => $value) {
    if(strpos($value, " ") !== false) $columns[$num] = "`".$columns[$num]."`";
    $num = $num + 1;
    $values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}

$final_statement = "INSERT INTO " . $table_title . " (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;

如果有人认为有任何优化方法或使其更清洁......请随时发布内容!

再次感谢每个人的输入!

1 个答案:

答案 0 :(得分:1)

您可以使用简单的json_decode()implode()对其进行格式化并准备插入。考虑这个例子:

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns

$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES ('".implode("','", $data)."')";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save','GameScore','0','SeanPlott','1337')

编辑:假设您的列具有int类型(尤其是具有数值的类型)。无论出于何种原因它都不起作用,因为不匹配,如果是这样,你可能会这样做。考虑这个例子:

$raw_data = '{"command":"save","classname":"GameScore","cheatMode":"0","playerName":"SeanPlott","score":"1337"}';
$data = json_decode($raw_data, true);
$columns = array_keys($data); // get the columns

$values = array();
foreach($data as $key => $value) {
    // if not numeric, add quotes, if not, leave it as it is
    $values[] = (!is_numeric($value)) ? "'".$value."'" : $value;
}

$final_statement = "INSERT INTO `table` (".implode(', ', $columns).") VALUES (".implode(', ', $values).")";
echo $final_statement;
// outputs: INSERT INTO `table` (command, classname, cheatMode, playerName, score) VALUES ('save', 'GameScore', 0, 'SeanPlott', 1337)
// Note: numbers has no qoutes