3 回答

TA贡献1777条经验 获得超10个赞
使用array_column()witharray_search()获取需要修改的数组键。请参阅以下代码片段:
<?php
// Here is trick; get the key of the array using array_column
$key = array_search('2', array_column($array, 'place'));
// If any key found modify the array
if ($key && array_key_exists($key, $array)) {
$array[$key] = [
'id' => 7,
'type' => 1,
'place' => 2,
'description' => 'This is item place 2',
'image' => 'this_is_the_image.png',
];
}
print_r($array);
查看演示

TA贡献1802条经验 获得超6个赞
尝试 :
for($count=1;$count <= 3;$count++){
if(array_search($count,array_column("place",$array_from_db)) continue;
$places_array = array(
"id" => "3",
"type" => "default",
"place" => $count,
);
}
这将跳过:
Array
(
[id] => 3
[type] => default
[place] => 2
)
=========== 编辑 ==============
while($arr = $stmts->fetch())
{
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $arr['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
for($count=1;$count <= $max_places;$count++){
if(!isset($array[$count])){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
}
ksort($array);

TA贡献1852条经验 获得超7个赞
找到答案了,谢谢大家的帮助。
这是诀窍
首先我们需要像这样确定主数组
for($count=1;$count <= $max_places;$count++){
$array[$count] = array(
"id" => $res['id'],
"type" => "default",
"place" => $count
);
}
然后我们需要找到哪个地方不可用并显示匹配项。
while($arr = $stmts->fetch()){
$key = array_search($arr['place'], array_column($array, 'place'));
$key+=1;
if($key && array_key_exists($key, $array)) {
$array[$arr['place']] = [
"id" => $arr['id'],
"type" => $res['type'],
"place" => $arr['place'],
"url" => $arr['url'],
"image" => $arr['image']
];
}
}
诀窍在于
$key+=1;
因为数组中的默认键是0。希望这可以帮助别人
- 3 回答
- 0 关注
- 131 浏览
添加回答
举报