JohnSan
JohnSan

Reputation: 53

PHP / Jquery multidimensional array

I need to return a PHP array to Jquery, with the following format:

{
  labels: [1, 2, 3],
  series: [
    [
      {meta: 'description', value: 1},
    ],
  ]
}

How can I do this? I tried a few ways, and the one I came closest to is an index inserted in the path.

$return = array(
                 "labels" => [1,2,3],
                  "series" => [
                        array(
                            "meta" => ['description'],
                            "value" => [1],

                        ),
                    ],  

                );

Upvotes: 1

Views: 57

Answers (2)

Akram Hossain
Akram Hossain

Reputation: 400

You could try this...

<?php
    
    $return = array(
                     "labels" => [1,2,3],
                      "series" => [
                            array(
                                (object)[
                                    "meta" => 'description',
                                    "value" => 1,
                                ]
                            ),
                        ],  
    
                    );
    
    echo '<pre>';
    print_r($return);
    print_r(json_encode($return));
    echo '</pre>';

Upvotes: 0

El_Vanja
El_Vanja

Reputation: 3983

You were close, you just have to make two corrections:

  • there's an array level missing under series
  • value and meta values shouldn't be arrays

Your array should look like this before encoding:

$return = array(
    "labels" => [1,2,3],
    "series" => [ // numeric array, will be encoded as array
        [ // also numeric array, will be encoded as array (this one was added)
            array( // associative array, will be encoded as object
                "meta" => 'description', // value not placed in an array
                "value" => 1, // value not placed in an array
            ),
        ],
    ],
);

Upvotes: 1

Related Questions