将数组插入 PHP 数组
Inserting Array into PHP Array
正在处理具有以下结构的数组文件。我知道每个数组下面需要插入额外的数组 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
创建此数组后,我将使用一个列表循环遍历以验证列表中的每个值是否按如下方式放置在每个 'color' 数组中
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
为简单起见,我的控制列表看起来像
随风而逝
跨越鸿沟
金手指
完成后,我应该将 Across The Great Divide 的信息插入 'color'=> 'category a' 作为 [2],Goldfinger 向下移动一位。在 'color'=>category_b' 中,第一个数组应该是 Gone With The Wind。 'color' 数组中的任何一个都可能在任何位置缺少一个数组。总结一下,需要检查列表中是否存在某个值,如果不存在则插入数组。除了使用所示的 foreach 循环之外,还有更简单的方法吗?如果不是,我怎样才能将信息插入到正确的位置?
谢谢
编辑:
我相信这个问题可能还不清楚。我需要做的是检查一个数组是否存在于另一个数组中。如果conrollist中的值不在数组中,则根据conrollist中的位置向数组中插入一个数组。插入的数组将具有与其他数组相同的结构(我可以处理这部分)。我无法确定它是否存在以及是否插入它。希望这有帮助
您可能希望改用 for
循环,这样每次迭代都有一个指针以确定您在数组中的位置。
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
正在处理具有以下结构的数组文件。我知道每个数组下面需要插入额外的数组 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
创建此数组后,我将使用一个列表循环遍历以验证列表中的每个值是否按如下方式放置在每个 'color' 数组中
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
为简单起见,我的控制列表看起来像 随风而逝 跨越鸿沟 金手指 完成后,我应该将 Across The Great Divide 的信息插入 'color'=> 'category a' 作为 [2],Goldfinger 向下移动一位。在 'color'=>category_b' 中,第一个数组应该是 Gone With The Wind。 'color' 数组中的任何一个都可能在任何位置缺少一个数组。总结一下,需要检查列表中是否存在某个值,如果不存在则插入数组。除了使用所示的 foreach 循环之外,还有更简单的方法吗?如果不是,我怎样才能将信息插入到正确的位置? 谢谢
编辑: 我相信这个问题可能还不清楚。我需要做的是检查一个数组是否存在于另一个数组中。如果conrollist中的值不在数组中,则根据conrollist中的位置向数组中插入一个数组。插入的数组将具有与其他数组相同的结构(我可以处理这部分)。我无法确定它是否存在以及是否插入它。希望这有帮助
您可能希望改用 for
循环,这样每次迭代都有一个指针以确定您在数组中的位置。
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}