php数组和json数组之间的互相转化的微妙差异

今天在修改一个接口时发现,突然间不能正常显示,排查后发现是接口返回的json对象中某个节点由数组变成了对象导致解析出错。

$a = array(
    0 => 1,
    1 => 'b',
    'c' => 'c'
);

echo json_encode($a);

{"0":1,"1":"b","c":"c"}


$b = array(
    0 => 1,
    1 => 'b',
    2 => 'c'
);
echo json_encode($b);

[1,"b","c"]

$b = array(

    1 => 'b',
    2 => 'c'
);
echo json_encode($b);
{"1":"b","2":"c"}


$c = array(
    0 => 1,
    1 => 'b',
    3 => 'c'
);

echo json_encode($c);

{"0":1,"1":"b","3":"c"}


$d = array(
	0 => 1,
	1 => 'b',
	3 => array(
		'name' => 'mike',
		'sex' => 'man',
		"score" => array(1,2,3,4,5,6,7,8),
		"soore_b" => array(1,2,3,4,5,6,7,"t"=> 8)
	),
);

echo json_encode($d);die();
{
	"0": 1,
	"1": "b",
	"3": {
		"name": "mike",
		"sex": "man",
		"score": [1, 2, 3, 4, 5, 6, 7, 8],
		"soore_b": {
			"0": 1,
			"1": 2,
			"2": 3,
			"3": 4,
			"4": 5,
			"5": 6,
			"6": 7,
			"t": 8
		}
	}
}

 

// 在纯数字下标,且是自然顺序排序的时候,即从0开始没有间隔的依次排序的,则json会自动省略数字下标,此时,被转化为了一个json数组,而以字符串作为下标时,则转化为json对象了。 上面的最后一个例子很好地说明了其中的差异

你可能感兴趣的:(php)