搜索字符串嵌套数组 - PHP
我有一个有关嵌套数组的问题
dd($this->forest);
it give me this:
array:2 [▼
0 => array:3 [▼
"id" => 12
"location" => 'east'
"type" => 'reservation'
]
1 => array:3 [▼
"id" => 13
"location" => 'west'
"type" => 'rainforest'
]
2 => array:3 [▼
"id" => 14
"location" => 'north'
"type" => 'rainforest'
]
]
,所以我想搜索“沼泽”和“红树林”喜欢“ type” => '沼泽'或“ type” => “红树林”,但这些类型不在$ this-gt;森林中。因此,我已经使用IN_Array对其进行整理。
$this->typeOfForest = '';
foreach($this->forest as $item){
if(!in_array('swamp', $item)){
$this->typeOfForest = 'swamp_not_found';
break;
}
elseif(!in_array('mangrove', $item)){
$this->typeOfForest = 'mangrove_not_found';
break;
}
}
dd($this->typeOfForest);
但是当我dd($ this-> typeofforest); 它不会设置为$ this-> typeofforest ='swamp_not_found';而是$ this-> typeofforest ='mangrove_not_found';
另外,当我将新数据插入阵列$ this->森林中时;并再次运行in_array函数,它将给我$ this-> typeofforest ='swamp_not_found';而不是$ this-> typeofforest ='mangrove_not_found';
谢谢你!
I have a question regarding nested array
dd($this->forest);
it give me this:
array:2 [▼
0 => array:3 [▼
"id" => 12
"location" => 'east'
"type" => 'reservation'
]
1 => array:3 [▼
"id" => 13
"location" => 'west'
"type" => 'rainforest'
]
2 => array:3 [▼
"id" => 14
"location" => 'north'
"type" => 'rainforest'
]
]
so I want to search 'swamp' and 'mangrove' like "type" => 'swamp' or "type" => 'mangrove' but these type is not in the array of $this->forest. So, I have used in_array to sort it out.
$this->typeOfForest = '';
foreach($this->forest as $item){
if(!in_array('swamp', $item)){
$this->typeOfForest = 'swamp_not_found';
break;
}
elseif(!in_array('mangrove', $item)){
$this->typeOfForest = 'mangrove_not_found';
break;
}
}
dd($this->typeOfForest);
but when I dd($this->typeOfForest);
it will not set as $this->typeOfForest = 'swamp_not_found'; instead $this->typeOfForest = 'mangrove_not_found';
Also, when I insert new data 'swamp' into array $this->forest; and run again in_array function it will give me $this->typeOfForest = 'swamp_not_found'; instead of $this->typeOfForest = 'mangrove_not_found';
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如评论中所述,
in_array
函数不适用于多维数组。您需要使用array_column
功能来获取所有类型,然后进行查找。As said in the comments, the
in_array
function does not work with a multidimensional array. You need to use thearray_column
function to get all the types and then just do a lookup.您正在使用 in_array 函数,它只是在数组的每个索引中搜索给定值,但是由于您有一个二维数组,因此 in_array 无法找到任何值为“swamp”的索引,因此您的第一个 IF 条件变为 TRUE。
你可以这样做:
You are using in_array function, it just searches for a given value in every index of the array, But as you have a 2D array, So in_array cant find any index with value JUST 'swamp', so your first IF condition becomes TRUE.
You can do like this: