如何将ACF repeater获取的PHP数组传入JS并实现随机元素选取?
The core issue here is that you're using PHP's print_r() to output your array, which produces PHP-formatted text—not valid JavaScript. To fix this, we need to convert the PHP array to a JSON string (which is compatible with JS) and assign it directly to your JavaScript variables.
Here's the corrected code with explanations:
Step 1: Update the PHP Function to Return the Array
First, modify your function to return the array instead of printing it. This lets us convert it to JSON later:
<?php // Updated function to return the skill array instead of printing it function getSkillArray($list_name) { $skill = array(); if( have_rows($list_name) ) { while( have_rows($list_name) ) : the_row(); $sub_value = get_sub_field('quality'); array_push($skill, $sub_value); endwhile; } return $skill; } ?>
Step 2: Assign PHP Arrays to JavaScript Variables
Use json_encode() to convert the PHP array into a valid JavaScript array. This ensures the data is parsed correctly by JS:
<script> // Assign the ACF repeater data directly to JS variables using json_encode let description_list = <?php echo json_encode(getSkillArray('description_list')); ?>; let description_list_2 = <?php echo json_encode(getSkillArray('description_list_2')); ?>; // Initialize the hook once the page loads window.addEventListener('load', hook); function hook() { // Add a check to avoid errors if arrays are empty if (description_list.length === 0 || description_list_2.length === 0) { console.log("Warning: One or both skill lists are empty!"); return; } // Pick random elements from each array let randHook1 = description_list[Math.floor(Math.random() * description_list.length)]; let randHook2 = description_list_2[Math.floor(Math.random() * description_list_2.length)]; console.log(randHook1); console.log(randHook2); setTimeout(hook, 2000); } </script>
Key Changes Explained:
json_encode(): This function converts PHP arrays into JSON strings, which are valid JavaScript array literals. This is the proper way to pass data from PHP to JS.- Function Return: By having
getSkillArray()return the array instead of printing it, we can reuse it and format the output correctly for JS. - Empty Array Check: Added a guard clause to prevent runtime errors if your ACF repeater fields have no entries. This will log a warning instead of crashing the script.
This should resolve your issue—your JavaScript function will now have access to the correct arrays from your ACF repeater fields, and it can pick random elements as intended.
内容的提问来源于stack exchange,提问作者alan

