phparraysmultidimensional-array

Populate a 2d array from iterated database queries


I apologize a head of time for the lengthy/busy question. I am trying to take results from a MySQL query and base64_encode the Image blob data, return it to the array and then finally json_encode the results so I can use them in my Android application. I know everything on the Android side is set up properly.

What I have is the following:

PHP/SQL:

$query = "SELECT `locations`.`businessName`, `photos`.`img` 
        FROM `locations` 
        JOIN `photos` ON `locations`.`co_id` = `photos`.`co_id` 
        WHERE `locations`.`businessName` = '".$companyID."'";
            
    mysql_connect($dbserver, $dbusername, $dbpassword) or die(mysql_error());
    mysql_select_db($dbname) or die(mysql_error());
    
    $result = mysql_query($query) or die(mysql_error());  
    $num = mysql_numrows($result);
    $row = mysql_fetch_assoc($result);
    
    $i = 0;
    $rows = array();
    while ($i < $num) {
        
        $img = mysql_result($result, $i, "img");
        $finalImg['img'] = base64_encode($img);
        $businessName['businessName'] = mysql_result($result, $i, "businessName");
        
        $finalArray = array_push($rows, $businessName, $finalImg);
        // I know that array_push is pushing each variable as a separate array item
        // I tried creating an alternative variable that amends the two together
        // But that didn't work, result printed [Array, Array] [Array, Array]
        // Was I on the right track?

        $i++;
    }
    
    print json_encode($rows);

Returns 8 results:

[0] => {
    ["businessName"]=> string(12) "Some Company" }
[1] => {
    ["img"]=> string(145968) "/9j/4AAQSkZJRgABAQEAYABgAAD/4QIw..." }

What I need:

I want the results to appear like this, with only 4 results.

[0] => {
    ["businessName"] => string(12) "Some Company" 
    ["img"] => string(145968) "/9j/4AAQSkZJRgABAQEAYABgAAD/4QIw..." }
[1] => {
    ["businessName"] => string(12) "Some Company", 
    ["img"] => string(145968) "/9j/4AAQSkZJRgABAQEAYABgAAD/4QIw..." }

Android Application snippet:

jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject jObject = jArray.getJSONObject(i);
    String testerPhoto = jObject.getString("img");
    //Process image. Base64 decode... etc

Android Error:

07-18 11:28:52.573: E/onPostExecute(14562): FAILED: No value for img

Solution

  • Try this:

    array_push($rows, array_merge($businessName, $finalImg));