2012-05-08 04:51
浏览 55


I'm having problems translating my associative array that I create in jQuery to something I can access and use in PHP.

I use the following to build an associate array:

var colors = {};
$(this).find('input[name="color_id"]').each(function() {
    var color_entry_id = $(this).val();
    colors[color_entry_id] = jQuery.makeArray($(this).siblings(".colors." + $(this).val()).find(".img_color a.selected").map(function() {
        return $(this).css("background-color");

Basically, the above code should return something of the form:

colors = {
    "{{ color_entry_id }}": [array of string rgb values]

I then send it to my PHP script with the following:

     { "edit_colors": JSON.stringify(colors) },

In my PHP, I want to be able to grab the array corresponding to a {{ color_entry_id }} and loop through the values to use in an update query. The following is my PHP code:

$check_colors = array(
    "rgb(204, 51, 51)" => "red",
    "rgb(102, 153, 204)" => "sky_blue",
    "rgb(0, 204, 51)" => "lime_green",
    "rgb(0, 102, 0)" => "dark_green",
    "rgb(153, 0, 0)" => "burgandy", 
    "rgb(255, 102, 51)" => "orange", 

$colors = json_decode($_POST['edit_colors']);

foreach($images as $color_entry => $image_link) {
    $update_color_query = "UPDATE color SET ";
    foreach(array_keys($check_colors) as $color) {
        if(in_array($color, $colors[$color_entry])) {
            $update_color_query .= $check_colors[$color] . "=1, ";
        } else {
            $update_color_query .= $check_colors[$color] . "=0, ";
    $update_color_query .= "image_url='$image_link' WHERE id=$color_entry";

In the above code, images is a separate array with corresponding {{ color_entry_id }}s and image links as well. $check_colors is a PHP hardcoded associative array of rgb values to human readable colors. My problem is that the link:

in_array($color, $colors[$color_entry])

throws a "Fatal error: cannot use type stdClass as array" because $colors[$color_entry] is not becoming the two dimensional array I'm trying to get it to be. So anyone know what I am doing wrong and how I can get this two dimensional array to loop through in my PHP code?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douluozhan4370 2012-05-08 05:04

    The error is exactly what it says: You can't use an OBJECT as an ARRAY. When you use json_decode, it defaults to an object. You need it to be an associative array.

    So change it to this:

    $colors = json_decode($_POST['edit_colors'], true);

    Now, you can iterate through $colors as you need.

    解决 无用
    打赏 举报

相关推荐 更多相似问题