PHP多維陣列KeyValue的使用

傑克.陳發表於2016-10-05
<?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);
?>

 


相關文章