1

I have a multidimensional array

$output=Array
    (
        [0] => Array
            (
                [0] => mov_1
                [1] => MY FAIR LADY
            )

        [1] => Array
            (
                [1] => mov_10
                [2] => love actually
            )
    )
    and two variables
    $avlblQnty=50
    $success= true

when i send these data via json

echo json_encode( array('movieData'=>$output,'stock'=>$avlblQnty,'sucess'=>$success));

it returns

{"movieData":[["mov_1","MY FAIR LAD],{"1":"mov_10","2":"love actually"}],"stock":0,"success":true}

but i need json encoded data properly so that i can create an select box on movieData using(movieData.length), so for that i want json edcoded data in below format so that i can retrive successfully

{"movieData":[{"mov_1":"MY FAIR LAD,mov_10":"love actually"}],"stock":0,"success":true}

i want to know how to send an array(multidimensional/associative) and some varaibles together through json?

UPDATE

I have made my array properly and after it I'm getting json encode array below

{"movieData":{"mov_10":"love actually","mov_1":"my fair lady"},"stock":20,"success":true}

Now how to know the length of moveData? i used data.movieData.length on jquery where I'm getting these value but it returns undefined

Rich
  • 5,316
  • 9
  • 35
  • 58
diEcho
  • 50,018
  • 37
  • 156
  • 230

2 Answers2

2

MovieData is an object, no more an Array, so you have to visit all the properties and count them manually, something like the code below

var theLength=0;
for(var propertyName in movieData) {
    // filtering out inherited properties
    if (movieData.hasOwnProperty(propertyName)) {
        theLength++;
    }
}
// now theLength represent the length of the array
Eineki
  • 14,008
  • 6
  • 47
  • 54
0

To pass more variables to the json_encode() you just need to add another level to the array you pass in, with top level sections for your different values.

If your array of movie data was in $movie_data then you'd create an array like the following:

$output_for_json = array(
  'movie_data' => $movie_data, 
  'stock' => $stock,
  'success' => $success
);

When you parse the json you will need to change the code using the data to reference the specific part of the array, like 'movie_data'

jerclarke
  • 790
  • 1
  • 7
  • 20