PHP 多维数组 Key Value的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 多维数组 Key Value的使用相关的知识,希望对你有一定的参考价值。

<?php
$user["60"] = array("id" => "60", "num" => "56", "count" => "31");
$user["61"] = array("id" => "61", "num" => "22", "count" => "34");
$user["59"] = array("id" => "59", "num" => "32", "count" => "43");
$user["56"] = array("id" => "56", "num" => "41", "count" => "38");
$user["57"] = array("id" => "57", "num" => "39", "count" => "65");

$values = array_values($user);//返回数组的所有值(非键名)
$keys = array_keys($user);//返回包含数组中所有键名的一个新数组

$iskey=array_key_exists("57",$user);//检查某个数组中是否存在指定的键名,如果键名存在则返回 true,如果键名不存在则返回 false。
$iskey=array_key_exists(57,$user); //结果同上,不依赖类型,数字 57 与字符串 "57" 是相同的。

$key =array_keys($keys,57) ;// 函数返回包含数组中所有键名的一个新数组。如果提供了第二个参数,则只返回键值为该值的键名。

$result[‘status‘] = 0;
$result[‘res‘]=count($key);

//$result[‘res‘] = $user;
//-----------返回值是对象:
//-----------{"status":0,"res":{"60":{"id":"60","num":"56","count":"31"},"61":{"id":"61","num":"22","count":"34"},"59":{"id":"59","num":"32","count":"43"},"56":{"id":"56","num":"41","count":"38"},"57":{"id":"57","num":"39","count":"65"}}}

//$result[‘res‘] = $values;
//-----------返回值是数组:
//-----------{"status":0,"res":[{"id":"60","num":"56","count":"31"},{"id":"61","num":"22","count":"34"},{"id":"59","num":"32","count":"43"},{"id":"56","num":"41","count":"38"},{"id":"57","num":"39","count":"65"}]}


//$result[‘res‘] = $keys;
//-----------返回值是key的一维数组:
//-----------{"status":0,"res":[60,61,59,56,57]}

//sort($user);//按key排序之后,key被过滤掉
//$result[‘res‘] = $user;
//-----------返回值是按key排序(不包括key)的多维数组:
//-----------{"status":0,"res":[{"id":"56","num":"41","count":"38"},{"id":"57","num":"39","count":"65"},{"id":"59","num":"32","count":"43"},{"id":"60","num":"56","count":"31"},{"id":"61","num":"22","count":"34"}]}


echo json_encode($result);
?>

 

以上是关于PHP 多维数组 Key Value的使用的主要内容,如果未能解决你的问题,请参考以下文章

php array_key_exists 的多维数组版本

php两个多维数组组合遍历

javascript es6 多维数组对象相同属性值{key:value}的求和

javascript es6 多维数组对象相同属性值{key:value}的求和

javascript es6 多维数组对象相同属性值{key:value}的求和

如何在PHP中通过分隔符将字符串分解为多维数组