如何分别获取键和值

时间:2018-08-26 14:07:04

标签: php arrays json

(请不要说这是重复的,我首先检查了here) 我有一个像这样的json文件

[{"studentName":"ali","studentPhone":"123"}, 

{"studentName":"veli","studentPhone":"134"}

需要分别获取键和值,我正在尝试类似

foreach ($jsonArray as $array ) {
    if(is_array($array)){

        while($bar = each($array)){
            echo $bar[1];
        }

但是给我这个输出:

ali123veli134hatca134dursun13444

我也尝试过这种方式:

if(is_array($array)){
    foreach ($array as $key => $value) {
        echo $value;
    }

2 个答案:

答案 0 :(得分:0)

使用json_decode()进行这种尝试,或使用array_column()仅获得studentName

使用正常的foreach:

<?php
$json = '[{"studentName":"ali","studentPhone":"123"}, {"studentName":"veli","studentPhone":"134"}]';
$array = json_decode($json,1); // the second params=1 makes json -> array
foreach($array as $key=>$value){
    echo $value['studentName']."<br/>";
    #echo $value['studentPhone']."<br/>";    
}
?>

使用array_column():

<?php
$json = '[{"studentName":"ali","studentPhone":"123"}, {"studentName":"veli","studentPhone":"134"}]';
$array = json_decode($json,1);
$names = array_column($array,'studentName');
print '<pre>';
print_r($names); // to get only studentName
print '</pre>';
?>

答案 1 :(得分:0)

首先,您需要解码json字符串,将其分配给一个变量,然后遍历该变量并回显名称(studenName)。

Ps:解码JSON数组后,我们可以使用->表示法在每一列中访问元素的名称,因为我们在该数组中存储了对象。 < / p>

// decoding the json string
$jsonArray = 
json_decode('[{"studentName":"ali","studentPhone":"123"}, 

{"studentName":"veli","studentPhone":"134"}]');
//loop through the array and print out the studentName
foreach($jsonArray as $obj) {
  echo $obj->studentName . ' ';
  // if you want to print the students phones, uncomment the next line.
  //echo $obj->studentPhone . ' ';
}
// output: ali veli