Reputation:
I have a php array value but i don't know how to print it. there is my php code
$json = array();
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
$json[] = $result;
}
}
And here is my array value
Array
(
[0] => Array
(
[locationid] => 1
[locationname] => Anantapur
[locationvalue] => 1.1
)
[1] => Array
(
[locationid] => 2
[locationname] => Guntakal
[locationvalue] => 1.2
)
[2] => Array
(
[locationid] => 4
[locationname] => Guntur
[locationvalue] => 1.3
)
)
I'm Trying like
echo $json['locationname'];
But It's Not working please help me
Upvotes: 0
Views: 124
Reputation: 1108
If you want json string try this:
echo json_encode($json);
after your loop.
Upvotes: -1
Reputation: 549
You can directly print the value of location, instead of creating a new array, unless you need it further.
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
echo $result['locationname'];
}
}
if you want to have $json, which is an associative array, you need to get into it, looping through it.
foreach($json as $key => $value){
echo $value['locationname'];
}
Upvotes: 1
Reputation: 893
The array you created is associative array. For loo through these type of arrays requires foreach. Visit http://php.net/manual/en/control-structures.foreach.php
foreach($json AS $key =>$value){
echo $value['locationname'];
}
Upvotes: 1
Reputation: 253
You have not need to make a new array after get the result. you can print your value within the loop
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
echo $result['locationaname'];
}
}
Upvotes: 1
Reputation: 9853
You need to loop
through your array
first. Try foreach
foreach($json as $j){
echo $j['locationname'];
}
Upvotes: 1