0

I'm constructing an array in PHP to use it in my Javascript code. So I'm looping over all the posts (Wordpress) and push all the values to a string - which is the Javascript array:

<?php while ( $loop->have_posts() ) : $loop->the_post(); 
    $title = get_the_title();
    $address = get_field('address');
    $phone = get_field('phone');

    $shops = $shops . "['".$title."','".$phone."','".$address."'],";

    echo $shops; // for testing.
endwhile; wp_reset_query(); ?>

The input of the address is street, number BREAKRULE zip and city. Example:

Sint Pieterskaai 39
8000 Brugge

And that specific breakrule breaks the string to use as an array in Javascript. Here is a screenshot of the HTML output:

enter image description here

As you can see, there is a <br> after the house number.

I have already tried to replace the $address variable with this, but without any luck:

$address = str_replace(array("\r", "\n", "<br>"), '', $address);
Dennis
  • 528
  • 3
  • 24

1 Answers1

1

As @u_mulder said in his comment, use json_encode to encode an PHP Array to JSON string instead of creating a strange string data, like you do here:

$shops = $shops . "['".$title."','".$phone."','".$address."'],";

After that in your JavaScript code you can use JSON.parse() to retrieve data in form of an Array as well. If you want to transfer data between PHP and JavaScript I would recommend using AJAX instead of inserting/echoing data directly to DOM.

That way your data will be more secure and can't be directly found on the markup. See this post for more information about it: https://stackoverflow.com/a/23740549/15182618

If you still prefer to do that this way then I have prepared a simple example for you:

In PHP you have:

<?php

$PHParray = ['Foo','Bar','Baz'];    //creating our Array in PHP - I assume you know how to do this in at least two ways :)

//adding values to our Array (you can use array_push or other method if you want)
$PHParray[] = 'Quo';
$PHParray[] = 'Vadis';

/*
... rest of the code ...
*/

//converting array to JSON string and adding it to the DOM of our site
echo '<div id="our-data" style="display: none;">'.json_encode($PHParray).'</div>';
?>

And then your HTML with JavaScript:

<!DOCTYPE HTML>
<html>
<head>

    <script>
        let dataDiv = document.getElementById("our-data"),  //getting element created earlier in PHP that contains our data as JSON string
            JSarray = JSON.parse(dataDiv.innerText);        //creating an Array from the JSON string
        dataDiv.remove(); //removing this element from the DOM after fetching data

        console.log(JSarray);
    </script>

</head>
<body>

</body>
</html>

Console output (I'm using Google Chrome):

enter image description here

As you can see it's an Array with the data we expected.

So, it's that simple. You can copy the code above and change it so it suits your needs. Cheers!

whocares4400
  • 106
  • 7