user9240510
user9240510

Reputation:

print array value in php

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

Answers (5)

Amr Berag
Amr Berag

Reputation: 1108

If you want json string try this:

echo json_encode($json);

after your loop.

Upvotes: -1

Annapurna
Annapurna

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

Sanjit Bhardwaj
Sanjit Bhardwaj

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

Gur Janjua
Gur Janjua

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

Sohel0415
Sohel0415

Reputation: 9853

You need to loop through your array first. Try foreach

foreach($json as $j){
    echo $j['locationname']; 
}

Upvotes: 1

Related Questions