json_encode vs var_dump on mysqli_connection
我们有一个这样的
1 |
1 2 3 4 | ["affected_rows"]=> int(0) ["client_info"]=> string(79)"mysqlnd 5.0.11-dev - ..." ["client_version"]=> int(50011) ... |
号
但
1 2 3 4 | "affected_rows": null, "client_info": null, "client_version": null, ... |
有没有办法让json_编码的字符串具有相同的值?
来自官方文件
Parameters
value
The value being encoded. Can be any type except a resource.
号
您提供的
从源代码来看,对于不受支持的类型(如资源),它将生成
1 2 3 4 5 | default: encoder->error_code = PHP_JSON_ERROR_UNSUPPORTED_TYPE; if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) { smart_str_appendl(buf,"null", 4); } |
我希望有人能做到这一点并分享解决方案。到目前为止还没有解决办法,所以我要尝试一下。
正如@rkosegi所指出的,
var_export will cast the resource to an array (mysqli::__set_state ) - sonull s again
foreach also treats it as an array and gives usnull s
var_dump could get the values (but could not be easily captured)
print_r however, gives us the values and could be saved
号
那么,让我们使用
1 |
号
通过一些字符串分析,我们可以得到我们想要的。
更新-添加带警告的字符串分析(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $link = mysqli_connect('localhost', 'root', 'lilo123', 'm1_s1'); $raw = print_r($link, true); $raw = explode(PHP_EOL, $raw); $link_arr = []; foreach($link as $k => $v) { $match = array_filter($raw, function($var) use ($k) { return strpos($var, '['.$k.']'); }); $val = array_values($match)[0]; if(strpos($val, ' => ')) { $val = explode(' => ', $val)[1]; $link_arr[$k] = $val; } } $link_json = json_encode($link_arr, JSON_PRETTY_PRINT); echo $link_json; |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "affected_rows":"0", "client_info":"mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $", "client_version":"50011", "connect_errno":"0", "connect_error":"", "errno":"0", "error":"", "error_list":"Array", <-- no good "field_count":"0", "host_info":"Localhost via UNIX socket", "info":"", "insert_id":"0", "server_info":"5.7.19-0ubuntu0.16.04.1", "server_version":"50719", "stat":"Uptime: 52396 Threads: 1 Questions: 36754 Slow queries: 0 Opens: 133 Flush tables: 1 Open tables: 60 Queries per second avg: 0.701", "sqlstate":"00000", "protocol_version":"10", "thread_id":"5274", "warning_count":"0" } |
。