我有一个数组$get_list_cate
。
所以,我想比较一下这个数组中两列的值。
数组$get_list_cate
:
ID..................PARENT_ID.....................NAME
0 5 Ashe
1 3 Garen
2 0 Yasuo
4 1 Miss Fortune
5 2 Veikor
因此,我尝试遍历此数组并尝试将id
的所有值与parent_id
的所有值进行比较。这是我的代码:
<?php foreach($get_list_cate as $item_cate):
if($item_cate->parent_id == $item_cate->id ) :
// some code
endif
endforeach
?>
但它会是这样的:
Only 5 is values of `parent_id` : - compare to - : all values in `id`.
5 ---- 0
---- 1
---- 2
---- 4
---- 5 -> correct.
停在这里。不是两个foreach
。
它应该继续:
3 ----- 0
---- 1
---- 2
---- 4
---- 5
=&GT;在这个数组中不可用。
0 ----- 0 -> correct.
---- 1
---- 2
---- 4
---- 5
越来越多......
答案 0 :(得分:2)
<强>说明:强>
->
,用于从数组中获取对象。 $data['DB COLUMN NAME']
的运算符来获取数据或随心所欲。$data
是循环中的变量。因此,这可能是您需要使用的代码。
如果你需要与
one foreach()
进行比较,你得到的是单个阵列。
<?php
foreach($get_list_cate as $single_item)
{
if($single_item['id'] == $single_item['parent_id'])
{
// You can handle upon the condition if TRUE
}
else
{
// You can handle the FALSE Request over here
}
}
?>
如果你需要与
Two foreach()
进行比较,你得到的阵列。
(例如)您需要比较来自ID
的{{1}}和来自first array
的{{1}}您可以使用以下代码
PARENT_ID
替代解决方案:
如果您有两个数组second array
和<?php
foreach($get_list_cate as $key1=>$single_item)
{
foreach ($single_item as $key2 => $single_value)
{
if($key2==$key1)
{
if($single_value['parent_id'] == $single_item['id'])
{
// You can handle upon the condition if TRUE
}
else
{
// You can handle the FALSE Request over here
}
}
}
}
?>
,则可以执行$array1
以便单独取出奇数。如果使用$array2
函数,它会从数组中提取出不同的值。
<强>代码:强>
array_diff()
<强>输出:强>
array_diff()
答案 1 :(得分:1)
使用嵌套循环
<?php
foreach($get_list_cate as $item_cate1):
foreach($get_list_cate as $item_cate2):
echo $item_cate1->parent_id . '----' . $item_cate2->id;
if($item_cate1->parent_id == $item_cate2->id ):
// some code
echo "-> correct";
endif
echo "<br>";
endforeach
endforeach
?>
答案 2 :(得分:1)
您提供的数据表明,id列中出现了四个父ID,而不是一个。即0,1,2&amp; 5.您可以将array_intersect函数与array_column函数结合使用来查找这些函数。
$parent = array_column($get_list_cate,'PARENT_ID');
$ids = array_column($get_list_cate, 'ID');
$intersect = array_intersect($parent, $ids);
然后只需遍历结果即可显示输出
答案 3 :(得分:-1)
您使用->
运算符,它用于对象。如果您调用的是#34; array&#34; $get_list_cate
是一个真正的数组:
foreach($get_list_cate as $item_cate):
if($item_cate['parent_id'] == $item_cate['id']) :
// some code
endif;
endforeach;