猿问

从 2 个数组在另一个数组中创建一个数组

我试图将某个数组中的某些项输入到另一个数组中,但是在创建该数组时,它不断添加不应该输入的项,例如


array(

       $parentcat ('id' =>'1000', 'name' => 'assets',)

                  ('id' => '2000', 'name' => 'expenses'),

       $categories('id' => '1100', 'name' =>'cash', ‘cat’ => 1000)

                  ('id' => '1200', 'name' => 'AR', ‘cat’ => 1000)

                  ('id' => '2100', 'name' => 'AP', ‘cat’ => 2000)

                  ('id' => '2200', 'name' => 'payroll', ‘cat’ => ‘2000’))

我尝试遍历每个数组并检查


for($k = 0; $k < count($parentCat); $k++) {

            for ($j = 0; $j < count($categories); $j++) {

                //echo $parentCat[$k]['id'] . ' ' . $categories[$j]['cat'];

                if ($parentCat[$k]['id'] == $categories[$j]['cat']) {

                //echo $categories[$j]['cat'] . '==' . $parentCat[$k]['id'];

                $categories_dropdown[$categories[$j]['id']] = $categories[$j]['name'];

                } 

                $parent[$parentCat[$k]['name']] = $categories_dropdown;

            }                

        }

我想要这个


$parentcat('assets' => array('id' =>'1100', 'name' => 'cash'),('id' =>'1200' 'name' => 'AR'),

          'expenses' => array('id' => '2100', 'name' => 'AP'),('id' => '2200' 'name' => 'payroll))



for some reason i get 


$parentcat('assets' => array('id' => '1100', 'name' => 'cash'),('id'=> '1200' 

 'name' => 'AR'),

          'expenses' => array('id' => '1100' => 'cash'),('id' =>'1200','name' => 'AR'),('id' => '2100', 'name' => 'AP'),('id' => '2200', 'name' => 'payroll))



拉风的咖菲猫
浏览 129回答 2
2回答

繁星点点滴滴

只需$parent[$parentCat[$k]['name']] = $categories_dropdown在if语句内部移动,否则无论条件是否满足,您都在分配变量,但只有在条件满足时,值才会改变。这就是为什么你得到意想不到的结果的原因。

牛魔王的故事

我不确定您在 $categories_dropdown 中想要的输出,但以下内容将为您提供 $parent 的预期输出。当您添加到数组时,它应该在 if 语句中<?php&nbsp;$parentcat = [['id' =>'1000', 'name' => 'assets'], ['id' => '2000', 'name' => 'expenses']];$categories = [ ['id' => '1100', 'name' =>'cash', 'cat' => '1000'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['id' => '1200', 'name' => 'AR', 'cat' => '1000'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['id' => '2100', 'name' => 'AP', 'cat' => '2000'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ['id' => '2200', 'name' => 'payroll', 'cat' => '2000']];for($k = 0; $k < count($parentcat); $k++) {&nbsp; &nbsp; for ($j = 0; $j < count($categories); $j++) {&nbsp; &nbsp; &nbsp; &nbsp; if ($parentcat[$k]['id'] == $categories[$j]['cat']) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $categories_dropdown[$parentcat[$k]['id']] = $categories[$j]['name'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $parent[$parentcat[$k]['name']][] = $categories[$j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}echo "<pre>";print_r($parent);echo "</pre>";?>
随时随地看视频慕课网APP
我要回答