5

PHP系列 | PHP索引数组和关联数组转json区别 - Tinywan

 2 years ago
source link: https://www.cnblogs.com/tinywan/p/16090180.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
PHP系列 | PHP索引数组和关联数组转json区别 - Tinywan - 博客园

什么是索引数组?

索引数组是指以数字为键的数组。并且这个键值是自增的

$indexArr = ["PHP","Java","Golang"];
var_dump($indexArr);

以上打印输出

array(3) {
  [0]=>
  string(3) "PHP"
  [1]=>
  string(4) "Java"
  [2]=>
  string(6) "Golang"
} 

键值是从0开始的一个索引 

索引数组转为json后是数组

echo json_encode($indexArr);

输出:["PHP","Java","Golang"]

数组转为json会是数组形式的

什么是关联数组?

关联数组指的是一个键值对应一个值,并且这个键值是不规律的,通常都是我们自己指定的。

$mapArr = ["name" => "Tinywan","age" => 24, "schoole" => "GanSu"];
var_dump($mapArr);
array(3) {
  ["name"]=>
  string(7) "Tinywan"
  ["age"]=>
  int(24)
  ["schoole"]=>
  string(5) "GanSu"
}

关联数组转为json后是对象

echo json_encode($mapArr);

输出:{"name":"Tinywan","age":24,"schoole":"GanSu"}

数组转为json会是对象形式的

所以关联数组我们也可以作为一个Map使用,类似于Python的集合

d = {key1 : value1, key2 : value2, key3 : value3 }

注意:dict 作为 Python 的关键字和内置函数,变量名不建议命名为 dict


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK