im trying to input certian items from an array into another array but as the array is being created it keeps adding items that are not suppose to go in for example
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’))
I tried looping through each array and checking if the
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;
}
}
and I want this
$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))
I'm not sure of the output you wanted in $categories_dropdown but the following will give you your expect output of $parent. When you add to the array it should be inside the if statement
<?php
$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++) {
if ($parentcat[$k]['id'] == $categories[$j]['cat']) {
$categories_dropdown[$parentcat[$k]['id']] = $categories[$j]['name'];
$parent[$parentcat[$k]['name']][] = $categories[$j];
}
}
}
echo "<pre>";
print_r($parent);
echo "</pre>";
?>
Simply move $parent[$parentCat[$k]['name']] = $categories_dropdown
inside the if
statement, otherwise you are assigning the variable no matter if the condition meets or not, but the value is only changing when the condition does meet. That's the reason why you are getting an unexpected result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.