0

I i made an array with variables adding strings and variables, and i want to add this string to another array, the problem is that when i console log it with javascript it shows as a string and not as an array, this also makes so i can't acces the array data. This is my code:

    foreach($datas as $data) {
        $currentusername = $data['username'];
        $currentpassword = $data['password'];
        $currentage = $data['age'];
        $objectresult = "['Username' => ${currentusername}, 'Password' => ${currentpassword}, 'Age' => ${currentage}]";
        
        print $objectresult."<br/>";
        array_push($usuarios, $objectresult);
    }
    ?>

    <script language="JavaScript">
        var num = <?php echo json_encode($usuarios) ?>;
        for(let i = 0; i < num.length; i++) {
            console.log(num[i]);
        }
    </script>
2
  • 2
    You build $objectresult as a string - is there any reason that you don't create it as an array? Commented Aug 22, 2021 at 18:16
  • 1
    PHP's json_encode() turns an array into a string. It sounds like you want to use Javascript's JSON.parse() function, e.g. var num = JSON.parse(<?php echo json_encode($usuarios) ?>). Commented Aug 22, 2021 at 18:17

1 Answer 1

1

Don't put the array in quotes, it should be an ordinary PHP array.

$objectresult = ['Username' => $currentusername, 'Password' => $currentpassword, 'Age' => $currentage];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.