I have created a JavaScript function that accepts 2 arrays in parameters and its goal is to be able to randomly select an index of each array. But my concern is that the data of my 2 arrays are retrieved with PHP via the ACF repeater.
<script>
// I call my JS function once the page is fully loaded
window.addEventListener('load', hook);
// Variable declaration
let description_list;
let description_list_2;
</script>
<?php
// The list_name param contains the name of the repeater field
function showSkill($list_name){
if( have_rows($list_name) ):
$skill = array();
while( have_rows($list_name) ) : the_row();
$sub_value = get_sub_field('quality');
array_push($skill,$sub_value);
endwhile;
print_r($skill);
else :
endif;
}
showSkill('description_list');
showSkill('description_list_2');
?>
<script>
function hook() {
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>
You can try inserting PHP Array into your JS, via json_encode
:
First, you need to set the PHP variables:
<?php
function showSkill( $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;
print_r( $skill );
endif;
// You need to return the array
return $skill;
}
// Get the returned array, convert to JSON and save into a variable
$description_list = json_encode( showSkill( 'description_list' ) );
$description_list_2 = json_encode( showSkill( 'description_list_2' ) );
?>
Then you can pipe the variables into JS:
<script>
let description_list = <?php echo $description_list; ?>
// 1. Parse JSON String to Object
description_list = JSON.parse(description_list);
// 2. Convert Object to Array
description_list = Object.values(description_list);
// 3. Do the same for description_list_2, or convert this process into a function
let description_list_2 = Object.values(JSON.parse(<?php echo $description_list_2)));
</script>
And run your JS hook()
function as usual.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.