(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;
}
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>';
?>
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