更改返回数组的ID

时间:2017-03-22 07:39:41

标签: php arrays

我有以下方法:

$results = array_filter($arr['people'], function($people) use ($searchId) {
    return in_array($searchId, $people['member']);
});

echo json_encode($results);

这回归了这样一个阵列:

[{"id":"8080","content":"foo","member":[123,456],"interval":7}]

但是如果有多个结果,它将返回:

["0": {"id":"8080","content":"foo","member":[123,456],"interval":7}]
["5": {"id":"8082","content":"bar","member":[1234,3456],"interval":5}]

我想用“Array”中的ID替换“自动”给定的ID - 如下所示:

["8080": {"id":"8080","content":"foo","member":[123,456],"interval":7}]
["8082": {"id":"8082","content":"bar","member":[1234,3456],"interval":5}]

有人有想法吗?

2 个答案:

答案 0 :(得分:0)

试试这个简单的方法:

$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);

答案 1 :(得分:0)

试试这个,

$arr = [
    0 => [
        "id"       => 8082,
        "content"  => "test",
        "interval" => "7",
    ],
    5 => [
        "id"       => 8086,
        "content"  => "test",
        "interval" => "7",
    ],
];

$ids    = array_column($arr, "id");
$result = array_combine($ids, $arr);
print_r($result);
echo json_encode($result);

array_column表示返回输入数组中单个列的值 array_combine哪些状态通过使用一个数组作为键来创建一个数组,另一个数组用于其值。