【问题标题】:Translating two dimensional associative jquery array to php array将二维关联 jquery 数组转换为 php 数组
【发布时间】:2012-05-16 14:07:14
【问题描述】:

我在将我在 jQuery 中创建的关联数组转换为我可以在 PHP 中访问和使用的东西时遇到问题。

我使用以下来构建一个关联数组:

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");
    }));
});

基本上,上面的代码应该返回以下形式:

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

然后我将其发送到我的 PHP 脚本,并带有以下内容:

$.post(
     "test.php",
     { "edit_colors": JSON.stringify(colors) },
    ...
);

在我的 PHP 中,我希望能够获取与 {{ color_entry_id }} 对应的数组并循环遍历要在更新查询中使用的值。以下是我的 PHP 代码:

$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";
    mysql_query($update_color_query);
}

在上面的代码中,images 是一个单独的数组,其中包含相应的 {{ color_entry_id }} 和图像链接。 $check_colors 是一个 PHP 硬编码关联数组,由 rgb 值与人类可读颜色组成。我的问题是链接:

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

抛出“致命错误:不能使用类型 stdClass 作为数组”,因为 $colors[$color_entry] 没有成为我想要的二维数组。所以有人知道我做错了什么以及如何让这个二维数组在我的 PHP 代码中循环?

【问题讨论】:

    标签: php jquery json associative-array


    【解决方案1】:

    错误正是它所说的:您不能将 OBJECT 用作 ARRAY。当您使用 json_decode 时,它​​默认为一个对象。你需要它是一个关联数组。

    所以改成这样:

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

    现在,您可以根据需要遍历 $colors。

    【讨论】:

    • 哇,我什至没有看到文档的那部分。感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2020-04-20
    • 2011-05-08
    • 2016-02-18
    相关资源
    最近更新 更多