0

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);
});
2
  • 1
    You should learn the difference between JSON and an actual array. Commented Jun 13, 2018 at 10:58
  • Add your JavaScript function to the question please. Your problem is, that your JSON is interpreted as a string in JavaScript, instead of an array of objects. To help you solve the problem we need a glimpse at your JS code. Commented Jun 13, 2018 at 11:00

4 Answers 4

3

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])

Sign up to request clarification or add additional context in comments.

4 Comments

you're accessing the first element of a JSON object -> You're accessing the first element of a JSON string thus returning the first character.
I tried but give me this now: [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object], [object Object] , I modified the post by adding my code
Of course, you're are using alert, it will never show you the actual object, just [object Object]. Always use console.log to debug your code!!!
Great Stefano, Don't forget to upvote / accept answer(s) you felt helped solve you problem for future reference.
0

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.

Comments

0

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]);
    }

Comments

0

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"
        }]
    ]
};

Comments

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.