php 总结(6) Json格式数组转换

1.对变量进行Json编码 和解码

$arr = array(1,2,3,4,5,6,"hello","nice" );
print_r($arr);
// Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => hello [7] => nice )   普通输出
echo "<br>";
echo json_encode($arr);
 // [1,2,3,4,5,6,"hello","nice"]
echo "<br>";
echo $arr[0]."<br>";
// 1
$obj = array('1'=> 3,'2'=>'nice' );
echo json_encode($obj);
// {"1":3,"2":"nice"}
echo "<br>";
print_r($obj[2]);
// nice

2.解码变量   

$jsdata ='{"h":"hello","w":"world","0":[3,2,1] }';

$jss = json_decode($jsdata);
print_r($jss);
echo  "<br>";
echo $jss->h;

3.写入和读取数据  

// 写入数据
$f=fopen('data', 'a');
fwrite($f, 'hello4');
fclose($f);
echo "ok";
// 读取数据 只能读到一行
$r = fopen('data', 'r');
$content=fgets($r);
echo $content;

fclose($r);

// 读取全部数据
echo file_get_contents('data');

  

  

 

猜你喜欢

转载自www.cnblogs.com/nice2018/p/10302134.html