Search code examples
phparraysjsonwhile-loopgetjson

PHP Array in wrong format


I have a query which I want the results inserted in an array so after all I'll encode it into a JSON, but my problem is that I want the data to be set like this:

array[0] = project1, project2, project3; array[1] = item1, item2, item3;

and I'm having this:

array[0] = project1; array[1] = project2; array[2] = project3;

and so on..

this is what I've done so far:

$info = array();

    $items = mysql_query("SELECT * FROM `vision`.`projects` WHERE  proj_area = 'area_1'");

        if (mysql_num_rows($items) != 0) { 
            while($proj = mysql_fetch_array($items)) {      

            $proj_name = $proj['proj_name'];
            $proj_beg = $proj['proj_beg'];
            $proj_end = $proj['proj_end'];

            array_push($info, $proj_name, $proj_beg, $proj_end );
        } 
    }

    echo json_encode($info);

my query result gave me these result:

["nome", "0000-00-00", "0000-00-00", "Projeto 2", "2016-12-12", "2020-07-30", "Projeto", "2017-02-03", "2018-03-10"]

and this is my $.getJSON code:

$.getJSON("includes/get_area.php",function(data){

                    console.log(data);
                    })

What am I doing wrong?


Solution

  • Try this one; this will add a list in each one of the three array indexes.

    $info = array();
    
    $items = mysql_query("SELECT * FROM `vision`.`projects` WHERE  proj_area = 'area_1'");
    if (mysql_num_rows($items) != 0) {
        while($proj = mysql_fetch_array($items)) {
            $info[0][] = $proj['proj_name'];
            $info[1][] = $proj['proj_beg'];
            $info[2][] = $proj['proj_end'];
        }
    }
    
    echo json_encode($info);