使用来自多维PHP数组的特定键作为Javascript变量Jquery onClick [关闭]

I have a multi-dimensional PHP array where the key for each inner array is an ID of button I will be clicking and instantiating a jQuery function.

I basically want to dynamically create a javascript VAR array from that PHP array based on the Id that is clicked. Here is the array:

$ContentGroupIds = array(
    43 => array( 511, 531, 567 ),
    54 => array( 483, 499, 509 )
);

So you can see I have ContentGroupId's: 43 and 54 which each point to an array of ContentId's.

When I click on the button for ContentGroupId = 43, I need to dynamically set the jquery var to look like this:

var contentids = ['511','531','567'];

Then I can use that var in the rest of my jquery function.

Set the ContentGroupID's as an attribute on your buttons (having your HTML output would help), and grab that attribute with jQuery.

PHP/HTML:

<?php
    $ContentGroupIds = array(
        43 => array( 511, 531, 567 ),
        54 => array( 483, 499, 509 )
    );

    foreach( $ContentGroupIds as $item => $ids ){
        // Convert ID Array to string
        $attr = implode( ',', $ids );

        // Output: <a href="#" class="btn" attr-ids="511,531,567">Button #43</a>
        echo '<a href="#" class="btn" attr-ids="'. $attr .'">Button #'. $item .'</a>';
    }
?>

jQuery:

$('body').on('click', '.btn', function(){
    var str = $(this).attr('attr-ids'),  // str = "511,531,567"
        arr = str.split(',');     // arr = ['511','531','567']

    console.log(arr); // (3) [0:"511", 1:"531", 2:"567"]
});

Functional Snippet:

$('body').on('click', '.btn', function(){
    var str = $(this).attr('attr-ids'),
        arr = str.split(',');

    alert(arr);
});
/*CSS only to make the links more buttony*/a{display:inline-block;background:#0095ff;padding: 6px 18px;color:#fff;text-decoration:none;border:1px solid #07c;box-shadow:inset 0 1px 0 #66bfff;font-family:sans-serif;font-size:14px border-radius:3px;}a:hover{background: #0085ee;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="btn" attr-ids="511,531,569">Button #43</a>
<a href="#" class="btn" attr-ids="483,499,509">Button #54</a>

</div>

You can convert a php array into javascript json using php json_encode