-1

This is the array of objects.

let arr=[
    {
        'teacherName':'skg',
        'subjectName':'c',
        'totalClass':4
    },
    {
        'teacherName':'skg',
        'subjectName':'php',
        'totalClass':4
    },
    {
        'teacherName':'skg',
        'subjectName':'js',
        'totalClass':4
    },
]

This is jQuery I used to send the data.

$('#myForm').submit(function () {
        console.log(arr);

        console.log('submit');
        $.ajax({
            type: 'POST',
            url: 'http://localhost/Backend/check.php',
            data: {
                arr: arr
            },
            success: function (data) {
                $('#output').html(data);
            }
        })

    })

I did not tried anything because I do not know what to do.

  • Welcome to Stack Overflow! Please visit [help], take [tour] to see what and [ask]. Do some research, ***[search for related topics on SO](https://www.google.com/search?q=convert+javascript+array+to+php+array+site:stackoverflow.com)***; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan Jan 08 '23 at 15:35
  • Associative array has keys defined in PHP, so you need to add key names to your `arr`. Just _why_ you need that? Why `$_POST['arr']` must be associative? – Justinas Jan 08 '23 at 15:37
  • If you want to index that array by e.g. `subjectName`, then use `array_column($_POST['arr'], null, 'subjectName')` – Justinas Jan 08 '23 at 15:38
  • You could sent the data encoded to a JSON string just replace your `arr` with `JSON.stringify(arr)` and from PHP script get is using: // Takes raw data from the request `$json = file_get_contents('php://input');` // Converts it into a PHP object `$data = json_decode($json);` – Lepy Jan 08 '23 at 17:22

1 Answers1

0

I'm not familiar with jquery, but normally in php you'd receive it via $_POST['arr'] and to convert json string into associative array you'd need use json_decode() function:

<?php
if (isset($_POST['arr']))
{
  $data = json_decode($_POST['arr']);
}
?>

However, depending on how jquery sends data to the server, you might need change your php to something like this instead:

<?php
$data = json_decode(file_get_contents("php://input"));
if ($data)
{
  //data received
}
?>
vanowm
  • 9,466
  • 2
  • 21
  • 37