How to get the array object value in php? - php

I am new to php, for my android application I am using php. My problem is I can not able to access the array object value.
Store the select query table value like below
$rows = array();
$i=0;
while($r = mysqli_fetch_assoc($result)) {
$rows[$i] = $r;
$i++;
}
When I display the value using echo json_encode($rows); it will display [{"CurrentVersion":"0.0.1","ForceUpdate":"1"}] this value. But when I trying to access this value in php I can not able to access I tried the below methods.
echo $verDetails[0].ForceUpdate; => ArrayForceUpdate <- I got this value
echo $verDetails[0] => Array <- I got this value
echo $verDetails[0]->ForceUpdate;=> Nothing got
I want to get the Forceupdate value = 1. Please help me, I know many one feel this is the cheap question and you will put negative vote, but I don't have other option. I tried in many ways but I am not get any answers.

mysqli_fetch_assoc returns an associative array. So you have to access the values like this:
$verDetails[0]['ForceUpdate']
To use the arrow syntax, use mysqli_fetch_object:
while($r = mysqli_fetch_object($result)) {
$rows[$i] = $r;
$i++;
}

You have multidimensional array try like this..
echo $rows[0]['CurrentVersion'];
echo $rows[0]['ForceUpdate'];
If you have json format data.use json_decode() to convert it into array.Then access each element.like this
$json = '[{"CurrentVersion":"0.0.1","ForceUpdate":"1"}]';
$rows = json_decode($json,true);
echo $rows[0]['CurrentVersion']."<br/>";
echo $rows[0]['ForceUpdate'];

Related

while loop into in array

What am I trying to do is collect data from a while loop, store it into a variable. Then later in my code I see if some variable is equal to one of the values in the array and then to echo out the two other column values I got from the while loop but equal to the row that the value came from. I have tried a bunch different things and am so close but cant get it exactly.
while($row = mysql_fetch_assoc($query)){
$team[] .= "{$row['team']}";
$winslosses .= "({$row['wins']} - {$row['losses']})";
}
this returns something like
$team = (bears, badgers, wildcats)
$winslosses = ((42-24), (55-23), (32-21))
Then later in my code I want to see if its equal to a value in the array then echo $winslosses.
if(in_array(bears, $team) ) {echo '$winslosses';}
This shows all the wins and losses from each team. I want it only show me the record of the bears.
Any help would be great.
You can use array_search() to get the index of an item in an array. You can then use that index when querying $winlosses:
$team = array(bears, badgers, wildcats);
$winslosses = array("(42-24)", "(55-23)", "(32-21)");
$key=array_search(bears, $team);
echo $winslosses[$key]
results in:
(42-24)
Your best bet would be to store them in an associative array.
while($row = mysql_fetch_assoc($query)){
$winslosses[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Hope this helps
Your main problem is that you currently have $winslosses as a string, not an array, so you can't easily pull out the win/loss record for just one team.
There are several ways you could do this. The one that seems easiest to me would be to put it together as one array up front.
Something like...
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = "({$row['wins']} - {$row['losses']})";
}
Then later on...
if(array_key_exists("bears",$teams)) {
echo $teams["bears"];
}
Or even better, store the wins/losses as a sub-array, so you have structured data that you can format however you want later on.
while($row = mysql_fetch_assoc($query)){
$teams[$row['team']] = array("wins" => $row['wins'], "losses" => $row['losses']);
}
echo $teams['bears']['wins']; // for example
Use associative array:
while($row = mysql_fetch_assoc($query)){
$team[] = {$row['team']};
$winslosses[$row['team']] = "{$row['wins']} - {$row['losses']}";
}
Then retrieve it like this:
if(in_array(bears, $team) ) {
echo $winslosses['bears'];
}
As a matter of fact, if you do not need the names of the teams in a separate array, you can just use one associative array and then retrieve it.
if (array_key_exists('bears', $winslosses)) {
echo $winslosses['bears'];
}

Best format for JSON encoding?

I'm not familiar with PHP and JSON but need it for my Android project.
I'm confused about which JSON format is the most effective. Most examples I saw use Associative array by using this code:
$result = mysql_query($queryString)
while($row = mysql_fetch_assoc($result)){
$json['contact']['ID'] = $row['ID'];
$json['contact']['Name'] = $row['Name'];
}
Format #1
{"contact":{"ID":"1","Name":"Andy"}}
I like that format but I don't know how to make each key hold more than one value. So when my query returns Andy and Bob, the json will only contains Bob.
Then, I found this PHP code:
while($row = mysql_fetch_row($result)){
$json['contact'][] = $row;
}
echo json_encode($json);
It makes the json looks like this:
Format #2
{"contact":[["1","Andy"],["2","Bob"]]}
But in Android, there is no JSONObject method to getArray(). Even if there is, I want to avoid using numbered array that requires [0] or [1] to be called.
So, which one is better? Or any other alternative?
Thanks
It's not that one method is more "effective" than the other, they serve different purposes. One is an associative object, and the other is a indexed array.
In your case, it looks like you want a list (indexed array) of objects. So what i would recommend doing is:
$result = mysql_query($queryString)
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json['contact'][] = $row;
}
echo json_encode($json);
which would result in the json:
{"contact":[{"ID":"1","Name":"Andy"}, {"ID":"2","Name":"Bob"}]}
Why not use mysql_fetch_array(); ?
{"contacts":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}
An object with key contacts that contain an array of contact objects perhaps?
You can also do it hardcoded (not as nice as mysql_fetch_array() tho.);
$result = array();
$i = 0;
while(...) {
$result[] .= '{"id":"'.$i.'","name":"'.$fetch['name'].'"}';
$i++;
}
echo "[".implode(',', $result)."]";

Json encode error from mysql result

I have done a little research on the following error Warning: [json] (php_json_encode) type is unsupported, encoded as nullbut have not found much in the way of answers?
I am trying to encode the result of a mysql query. Not sure what info I can provide.. but when I echo the results of the mysql data using
$data = json_encode($result);
echo $data;
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
for($i=0;$i<$count;$i++){
echo $content[$i]['Name'];
}
every thing shows as normal. Any help would be great.
What about:
$result=array();
for($i=0;$i<$count;$i++)
{
$result[]=$content[$i]['Name'];
}
echo json_encode($result);
mysql_fetch_array will return an array with both numeric and non-numeric values. That's fine for PHP, but it doesn't really play as well in other formats and it could very well be the cause of the issue. Have you tried mysql_fetch_assoc?
BIG EDIT
Just noticed your code above. You have :
$data = json_encode($result);
echo $data;
while($info = mysql_fetch_array($result))
That won't work. $result is a resource data type. It can't be serialized into something which can be read by json_encode. You have to create an array of its contents first and serialize that. Just making sure you know.

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

Disappear the arrays generated with mysql_fetch_array() after use?

I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got

Categories