Stefano
Stefano

Reputation: 83

PHP Javascript - Array multidimensional error

In practice, I create an array in PHP that then I pass to a JavaScript function.

So far so good. The array that the functions recieves is the following:

[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]

My problem is to get all the first array, that is this: {"firstname": "Micheal", "lastname": "Brown"}

and also the second array this: {"car": "Ford", "model": "Fiesta"}

I tried with alert (array [0]) but it only shows me this [

How can I do this?

I'll explain:

this is my php file:

class UserClasses
{
     public $firstname;
     public $lastname;
}

class CarClasses
{
     public $car;
     public $model;
}

if(isset($_POST['name'])){
     populate($_POST['name']);
}

function populate(){
//I abbreviated the function for simplicity

   $arrayUser = array();
   $arrayCar = array();

   $user = new UserClasses();
   $user->firstname = "Micheal";
   $user->lastname = "Brown";
   array_push($arrayUser, $user);

   $car = new CarClasses();
   $car->car = "Ford";
   $car->model = "Fiesta";
   array_push($arrayCar, $car);
   $arrayFinal = array($arrayUser, $arrayCar);

   print json_encode($arrayFinal);
}

and this is the function in javascript:

//Ajax for calling php function
$.post('Classes.php', { name: name }, function(data){
    var array = JSON.parse(data);
    var arrayT = array[0];
    alert(arrayT);
});

Upvotes: 0

Views: 76

Answers (4)

Rounin
Rounin

Reputation: 29511

You are dealing with 3 different Data Types:

  • a PHP Multidimensional Array
  • a JSON String
  • a Javascript Object

Each needs to be converted into the next.

  • A PHP Array is converted into a JSON String, via json_encode() (in PHP)
  • A JSON String is converted into a Javascript Object, via JSON.parse() (in Javascript)

Now you have a Javascript Object which you can interrogate and manipulate using Javascript.


PHP Multidimensional Array:

$My_PHP_Array = array(

    array(

        'firstname' => 'Michael'
        'lastname' => 'Brown'
    ),

    array(

        'car' => 'Ford'
        'model' => 'Fiesta'
    )
);

Convert PHP Multidimensional Array to JSON String:

json_encode($My_PHP_Array);

JSON String:

'{
    [
        [{
            "firstname": "Micheal",
            "lastname": "Brown"
        }],

        [{
            "car": "Ford",
            "model": "Fiesta"
        }]
    ]
}'

Convert JSON String to Javascript Object:

var myJavascriptObject = JSON.parse(myJSONString);

Javascript Object:

myJavascriptObject = {
    [
        [{
            "firstname": "Micheal",
            "lastname": "Brown"
        }],

        [{
            "car": "Ford",
            "model": "Fiesta"
        }]
    ]
};

Upvotes: 0

Ivan
Ivan

Reputation: 40768

Here's what is happening with your code: you're accessing the first element of a JSON string, so my guess is you will get its first character: [.

You need to convert your string into an actual array before accessing it!

Use JSON.parse:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

- MDN web docs

For example you can do:

const json = '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'

// that's what you have
console.log(json[0])

// that's what you want
array = JSON.parse(json)
console.log(array[0])

Upvotes: 3

Bhumi Shah
Bhumi Shah

Reputation: 9476

You can parse data and use it:

    var arr = '<?php echo '[[{"firstname": "Micheal", "lastname": "Brown"}], [{"car": "Ford", "model": "Fiesta"}]]'; ?>';
    var parsedarr =  JSON.parse(arr);

    for(var i=0;i<parsedarr.length;i++){
        console.log(parsedarr[i][0]);
    }

Upvotes: 0

Mantelijo
Mantelijo

Reputation: 121

First of all, if you are using json_encode to pass PHP array to JS, it encodes it to a JSON string. You have to parse it using JSON.parse() and only then the json string is transformed to regular array which you can use.

Upvotes: 0

Related Questions