1

I currently have an array that looks like this:

    [[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]

I'm using:

        preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($results));

to create an array that should look like this:

    [{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]

However I can't seem to get rid of the extra set of brackets.

My model:

    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);
return $results;

}

My controller:

    function test()
{
    $this->load->model('data');
    $series_data[] = $this->data->get_data();
    $data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
    preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($series_data));
    $this->load->view('chart', $data);
}

thanks in advance.

2
  • the two strings are clearly not related Commented Mar 9, 2014 at 23:23
  • Sorry, I just put the second one in for formatting. I'll edit it for less confusion. Commented Mar 9, 2014 at 23:25

1 Answer 1

3

Why use preg_replace.... this is simply json encoded data:

$string = '[[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]';
var_dump(
    json_encode(
        json_decode($string)[0]
    )
);
Sign up to request clarification or add additional context in comments.

3 Comments

I keep getting an array to string conversiona error. I'll put in all my code for better help
What version of PHP are you running?
Instead of preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($series_data)); simply do json_encode($series_data[0]);.... or even earlier: use $series_data = $this->data->get_data(); instead of $series_data[] = $this->data->get_data();

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.