我需要映射到现有的多维数组,并有条件地向每个数组对象添加一个新项。
如果原始数组为:
Array
(
[0] => Array
(
[id] => 4
[uid] => 1
[name] => Dave Spicer
[content] => another post
[post_date] => 2018-12-03 00:02:26
)
[1] => Array
(
[id] => 3
[uid] => 2
[name] => John Doe
[content] => some post
[post_date] => 2018-12-03 00:02:21
)
[2] => Array
(
[id] => 1
[uid] => 1
[name] => Dave Spicer
[content] => My first post!
[post_date] => 2018-12-02 23:21:07
)
)
我想遍历它,有条件地向每个数组对象添加一个新的键值对,这将导致像这样的新数组:
Array
(
[0] => Array
(
[id] => 4
[uid] => 1
[name] => Dave Spicer
[content] => another post
[post_date] => 2018-12-03 00:02:26
[liked] => YES
)
[1] => Array
(
[id] => 3
[uid] => 2
[name] => John Doe
[content] => some post
[post_date] => 2018-12-03 00:02:21
[liked] => NO
)
[2] => Array
(
[id] => 1
[uid] => 1
[name] => Dave Spicer
[content] => My first post!
[post_date] => 2018-12-02 23:21:07
[liked] => YES
)
)
我假设我需要创建一个新数组,并且不可能将其推入现有的多维数组中,因为这是我一直试图做的无济于事的方法,但是我可以完全那里错了。请让我知道是否是这种情况。
我尝试复制数组并在其上运行foreach
循环,但是只能在所有数组的末尾添加一个新的键值对作为新的数组对象。
有人可以指出我要在此处使用的正确功能的方向吗? array_merge
? array_combine
? array_push
?等等
答案 0 :(得分:1)
只需分配索引即可将元素添加到数组。
foreach ($array as $i => $element) {
$array[$i]['liked'] = get_like($element);
}
您还可以在foreach
循环中使用引用变量:
foreach ($array as $i => &$element) {
$element['liked'] = get_like($element);
}