PHP 中函数中的非法字符串偏移量


Illegal string offset in a function in PHP

我有这个PHP函数:

function editDatas($datas, $got, $to_find, $to_replace) {
    foreach($datas['datas'] as $key => $rows) {
        foreach($rows as $number => $row) {
            if($row['id'] == $got) {
                $datas['datas'][$key][$number][$to_find] = $to_replace;
                return $datas;
            }
        }
    }
}

而这个电话:

$datas = json_decode(file_get_contents('datas.json'), true);  
$datas = editDatas($datas, 'hotel_name', "value", 'My new hotel name');

我的json实际上是这样的:

{
    "datas": [
        {
            "category": "General",
            "id": "hotel_name",
            "type": "input",
            "maxlength": "15",
            "size": "10",
            "label": "Hotel name",
            "help": "Hotel name",
            "value": "Rubi's hotel"
        },
        ...

我正在尝试替换我的 json 中的一些值。

我面临的问题是这个错误:

Illegal string offset 'id' in line 33

在我的函数中是以下内容:

if($row['id'] == $got) {

我不明白为什么,因为id是知道的。

你能帮我解决我的问题吗?

谢谢。

我认为你的函数中有太多循环。试试这个:

function editDatas($datas, $got, $to_find, $to_replace) {
        foreach($datas['datas'] as $key => $row) {
            if($row['id'] == $got) {
                $datas['datas'][$key][$to_find] = $to_replace;
                return $datas;
            }
        }
    }

再想想你是如何迭代的,在何处迭代。

foreach($datas['datas'] as $key => $rows) {
// $key is 0, 1, ... and $rows is the object
    foreach($rows as $number => $row) {
    // $number is category, id, type ... and
    // $row is General, hotel_name, ...

知道了这一点,你可以重写你的 if 到

if ($number == 'id' && $row == $got) {
}

首先,请在json_decode后使用print_r函数打印数组 你会得到你的答案。