0

I have a problem visualizing arrays greater than one dimension. I did a query on a database table and stored the data in an array, then used mysqli_fetch_array() to create another array. Now this array has the table name and the table data in but I'm having trouble figuring out how to A) access just the data and B) visualize what is actually going on here.

This is the output of print_r($keystore);

Array ( [0] => Array ( [0] => 4 [key_projects] => 4 ) [1] => Array ( [0] => 26 [key_projects] => 26 ) [2] => Array ( [0] => 25 [key_projects] => 25 ) [3] => Array ( [0] => 52 [key_projects] => 52 ) [4] => Array ( [0] => 53 [key_projects] => 53 ) ) 

What exactly is going on here?

2 Answers 2

1

Sometimes it's helpful when developing/debugging code that has arrays, to insert the HTML <pre> tag before and after the print_r() command:

echo "<pre>";
print_r($keystore);
echo "</pre>";

This will force the output into a format similar to John Kugelman's answer (subject to CSS rules). I find, from experience, that each iteration of Array() will be indented, when viewing plain text (i.e. no HTML)

Sign up to request clarification or add additional context in comments.

Comments

0
Array
(
    [0] => Array ( [0] => 4  [key_projects] => 4  )
    [1] => Array ( [0] => 26 [key_projects] => 26 )
    [2] => Array ( [0] => 25 [key_projects] => 25 )
    [3] => Array ( [0] => 52 [key_projects] => 52 )
    [4] => Array ( [0] => 53 [key_projects] => 53 )
) 

I've added some whitespace to make the structure of the nested arrays clearer. I didn't change anything aside from adding spaces and newlines.

The outer array contains five entries from [0] to [4]. Each of these entries represents one row from the SQL result set.

for ($keystore as $row) {
    print_r($row[0]);
    print_r($row['key_projects']);
}

You'll notice the two entries in each $row are redundant. They both have the same value (e.g. 53 for the final entry). What's happening is the data is being returned indexed both by column number (0) and column name (key_projects). You can access the values using whichever one you choose, number or name: $row[0] or $row['key_projects'].

2 Comments

chance this has happened by not changing mysqli_fetch_array default resulttype value of MYSQLI_BOTH to MYSQLI_ASSOC thus returning numeric and associative array keys?
I solved the duplicate results by simply created another array and sticking each value in it. Pretty lame hack but it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.