-1

(please don't say this is a duplicate, I checked here first ) I have a json file like this

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

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

need to get keys and values separately I am trying something like this

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

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

but gives me this output :

ali123veli134hatca134dursun13444

I have also tried this way :

if(is_array($array)){
    foreach ($array as $key => $value) {
        echo $value;
    }
Jason
  • 15,017
  • 23
  • 85
  • 116

2 Answers2

0

Make a try like this way with json_decode() or use array_column() to get only studentName

Using normal 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/>";    
}
?>

Using 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>';
?>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

First of all you need to decode the json string, assign it to a variable, then loop through that variable and echo out the names (studenName).

Ps: after decoding the JSON array we can acces the elements' names in each column using the -> notation, as we have objects stored in that array.

// 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 
ThS
  • 4,597
  • 2
  • 15
  • 27