简体   繁体   中英

Generate nested array codeigniter

For a graph I'm working on, I'm trying to generate a nested array. I'm querying the database to try and get all the data from a certain column in my database as an array, but i'm not really quite sure how to do it. Currently it giving me the last row in my database.

Here is my code:

    function get_data()
{
    $this->db->select('ItemName, QuantitySold');
    $query = $this->db->get('transactions');

    $results = array();

    foreach ($query->result_array() as $row)
        {
           $row['QuantitySold'];
           $row['ItemName'];
        }

        $results = array(
            'name' => 'shirt',
            'data' => $row['QuantitySold']
            );
        $test = json_encode($results);
        echo $test;
        return $results;
}

It is generating this result:

    {"name":"shirt","data":"9"}

And I need it to look something like this:

    {'name':'shirt','data':array(1, 2, 3,...)}

Database Structure: http://d.pr/i/cQaW

Rows: http://d.pr/i/8vp2

 $result = array();

 foreach ($query->result_array() as $row)
 {
   //if new item, initiate array in order not to get an exception
   if( !isset($result[$row['ItemName']]) ) {
     $result[$row['ItemName']]['data'] = array();
     $result[$row['ItemName']]['name'] = $row['ItemName'];
   }
   //group data by item name

   $result[$row['ItemName']]['data'][] = $row['QuantitySold'];
 }

 echo json_encode($result);

Here is what I would do, note how I take the rows and store them differently than you currently do:

function get_data()
{
    $this->db->select('ItemName, QuantitySold');
    $query = $this->db->get('transactions');

    $results = array();

    foreach ($query->result_array() as $row)
    {
        $results[$row['ItemName']][] = $row['QuantitySold'];
    }

    $test = json_encode($results);
    echo $test;
    return $results;
}

Note that this isn't quite how you want the output, but it might be easier to process this way.

Output example:

{'shirt': [1, 2, 3], 'notshirt': [1, 2, 3]}

EDIT (for format):

function get_data()
{
    $this->db->select('ItemName, QuantitySold');
    $query = $this->db->get('transactions');

    $results = array();

    foreach ($query->result_array() as $row)
    {
        if(!isset($results[$row['ItemName']]))
            $results[$row['ItemName']] = array('name' => $row['ItemName'], 'data' => array());
        $results[$row['ItemName']]['data'][] = $row['QuantitySold'];
    }

    //Rekey arrays so they aren't associative
    $results = array_values($results);

    $test = json_encode($results);
    echo $test;
    return $results;
}

Output example:

{{name: 'shirt', data: [1, 2, 3], {'name': 'notshirt', data: [1, 2, 3]}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM