php in_array between 2 arrays - php

I am trying to determine which elements coincide in 2 arrays. The issue is that only the last element in my second array is selected instead of all 3. What am I missing here?
<?php
$containers = [
0 => ['id'=>'1', 'name'=>'Peta'],
1 => ['id'=>'2', 'name'=>'Epta'],
3 => ['id'=>'3', 'name'=>'Fras'],
4 => ['id'=>'4', 'name'=>'Maxs'],
5 => ['id'=>'5', 'name'=>'Gtay'],
6 => ['id'=>'6', 'name'=>'Prat'],
7 => ['id'=>'7', 'name'=>'Drat'],
];
$invoices = [
0 => ['id'=>'1', 'name'=>'Lebo'],
1 => ['id'=>'3', 'name'=>'Efta'],
2 => ['id'=>'4', 'name'=>'Gadr'],
];
foreach ($containers as $container) {
foreach ($invoices as $invoice) {
if (in_array($container['id'], $invoice)) {
$selected = 'selected';
} else {
$selected = '';
}
}
echo $container['name'].' -> '.$selected.'<br>';
} ?>

Add "break" after found in array.
<?php
$containers = [
0 => ['id' => '1', 'name' => 'Peta'],
1 => ['id' => '2', 'name' => 'Epta'],
3 => ['id' => '3', 'name' => 'Fras'],
4 => ['id' => '4', 'name' => 'Maxs'],
5 => ['id' => '5', 'name' => 'Gtay'],
6 => ['id' => '6', 'name' => 'Prat'],
7 => ['id' => '7', 'name' => 'Drat'],
];
$invoices = [
0 => ['id' => '1', 'name' => 'Lebo'],
1 => ['id' => '3', 'name' => 'Efta'],
2 => ['id' => '4', 'name' => 'Gadr'],
];
foreach ($containers as $container) {
foreach ($invoices as $invoice) {
if (in_array($container['id'], $invoice)) {
$selected = 'selected';
break;
} else {
$selected = '';
}
}
echo $container['name'] . ' -> ' . $selected . '<br>';
} ?>

$containers = [
[ 'id' => '1', 'name' => 'Peta' ],
[ 'id' => '2', 'name' => 'Epta' ],
[ 'id' => '3', 'name' => 'Fras' ],
[ 'id' => '4', 'name' => 'Maxs' ],
[ 'id' => '5', 'name' => 'Gtay' ],
[ 'id' => '6', 'name' => 'Prat' ],
[ 'id' => '7', 'name' => 'Drat' ],
];
$invoices = [
[ 'id' => '1', 'name' => 'Lebo' ],
[ 'id' => '3', 'name' => 'Efta' ],
[ 'id' => '4', 'name' => 'Gadr' ],
];
$result = array_filter(
$containers,
fn($item) => in_array($item['id'], array_column($invoices, 'id'))
);
print_r($result);
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Peta
)
[2] => Array
(
[id] => 3
[name] => Fras
)
[3] => Array
(
[id] => 4
[name] => Maxs
)
)

Seems the easiest solution was to create a new array:
foreach ($invoices as $invoice) {
$compare_id[] = $invoice['id'];
}
foreach ($containers as $container) {
if (in_array($container['id'], $compare_id)) {
$selected = 'selected';
} else {
$selected = '';
}
echo $container['name'].' -> '.$selected.'<br>';
}

Related

multidimensional array remove item from child array

i have a problem with my multidimensional array. I want to remove some items from child array by $id value.
here is my multidimensional example array and selectedIds:
$myArray = [
['id' => '2',
'name' => 'Punk'
],[
'id' => '5',
'name' => 'Rock',
'children' => [
'30' => ['id' => '30',
'name' => 'Hard Rock',
'parentId' => '5'
],
'40' => ['id' => '40',
'name' => 'Soft Rock',
'parentId' => '5'
],
'50' => ['id' => '50',
'name' => 'Glam Rock',
'parentId' => '5'
]
]
]
];
$selectedIds = [2,5,30];
and i want to remove from array those items which are not in selectedIds array.
so i want to have output:
$outputArray = [
[
'id' => '2',
'name' => 'Punk'
],[
'id' => '5',
'name' => 'Rock',
'children' => [
'30' => ['id' => '30',
'name' => 'Hard Rock',
'parentId' => '5']
]
]
];
i try to make it with foreach and array_key_exist but its not correct:
foreach ($myArray as $key=>$value) {
if (array_key_exists('children', $value)) {
foreach ($selectedIds as $id) {
if (isset($value['children'][$id])) {
$outputArray[] = $value['children'][$id];
}
}
}
}
print_r($outputArray);
this outpus is only item with id 30
write else part into your code if array has no children key
else{
foreach ($selectedIds as $id) {
if ($value['id'] == $id) {
$outputArray[$key] = $value;
}
}
}
Final code
<?PHP
$myArray = [
[
'id' => '2',
'name' => 'Punk'
],
[
'id' => '5',
'name' => 'Rock',
'children' => [
'30' => ['id' => '30',
'name' => 'Hard Rock',
'parentId' => '5'
],
'40' => ['id' => '40',
'name' => 'Soft Rock',
'parentId' => '5'
],
'50' => ['id' => '50',
'name' => 'Glam Rock',
'parentId' => '5'
]
]
]
];
$selectedIds = [2,5,30];
foreach ($myArray as $key=>$value) {
if (array_key_exists('children', $value)) {
foreach ($selectedIds as $id) {
if (isset($value['children'][$id])) {
$outputArray[$key]['id'] = $value['id'];
$outputArray[$key]['name'] = $value['name'];
$outputArray[$key]['children'][$id] = $value['children'][$id];
}
}
}else{
foreach ($selectedIds as $id) {
if ($value['id'] == $id) {
$outputArray[$key] = $value;
}
}
}
}
echo "<pre>";
print_r($outputArray);
?>
Output
Array
(
[0] => Array
(
[id] => 2
[name] => Punk
)
[1] => Array
(
[id] => 5
[name] => Rock
[children] => Array
(
[30] => Array
(
[id] => 30
[name] => Hard Rock
[parentId] => 5
)
)
)
)
Hey i make other code more simple. That´s here:
just change a bit the foreach content:
foreach ($myArray as $key=>&$value) {
if (array_key_exists('children', $value)) {
$value['children'] = array_intersect_key($value['children'], array_flip($selectedIds));
}
}
Use array_flipfor transform keys on values and array_intersect_keyfor get only they id´s that exist in 2 arrays.
here you can see a live demo
NOTE: take care that i´m passing the value by referer &$value in the foreach for modify the original array, if you dont want this just duplicate the original array and modify the second.

iterate over 2 arrays in PHP to display items with same account id

I have two classes containing informations about accounts and invoices like this
The accounts list
array (
0 =>
'id' => 1,
'username' => 'abc',
'company' => 'My Corporation',
)),
1 =>
'id' => 2,
'username' => 'cde',
'company' => 'My Company',
))
The invoice list
array (
0 =>
'account_id' => 1,
'invoiceId' => '15',
)),
1 =>
'id' => 2,
'account_id' => '2',
'invoiceId' => '17',
)),
2 =>
'account_id' => 1,
'invoiceId' => '20',
)),
3 =>
'id' => 2,
'account_id' => '2',
'invoiceId' => '30',
))
When iterating over both collections each invoice to be shown once. My issues is that everything will be duplicated
My code is
<?php
foreach ($invoices as $invoice) {
foreach($accounts as $account) {
echo $account->getUsername($invoice->getAccountId())."<BR>";
echo $account->getCompany($invoice->getAccountId());
}
}
I am not sure what I should do
I think this sould solve tour problem:
<?php
$accounts = array (
0 => array (
'id' => 1,
'username' => 'abc',
'company' => 'My Corporation',
),
1 => array (
'id' => 2,
'username' => 'cde',
'company' => 'My Company',
));
$invoices = array (
0 => array (
'account_id' => 1,
'invoiceId' => '15',
),
1 => array (
'id' => 2,
'account_id' => '2',
'invoiceId' => '17',
),
2 => array (
'account_id' => 1,
'invoiceId' => '20',
),
3 => array (
'id' => 2,
'account_id' => '2',
'invoiceId' => '30',
));
foreach($accounts as $account) {
foreach ($invoices as $invoice) {
echo "account id : ";
echo $account['id'];
echo "invoices: ";
if ( $invoice['account_id'] === $account['id'] ) {
echo $invoice['account_id'];
// echo $account->getUsername($invoice->getAccountId())."<BR>";
// echo $account->getCompany($invoice->getAccountId());
}
}
}

How to control the depth of php infinite pole classification

Here is my array:
$list = array(
array('id' => 3, 'name' => 'Phones', 'parent_id' => 0,),
array('id' => 256, 'name' => 'Accessories', 'parent_id' => 0,),
array('id' => 308, 'name' => 'Appliances', 'parent_id' => 0,),
array('id' => 1057, 'name' => 'Smart', 'parent_id' => 0,),
array('id' => 1065, 'name' => 'Smart Phones', 'parent_id' => 3,),
array('id' => 1066, 'name' => 'Feature Phones', 'parent_id' => 3,),
array('id' => 1069, 'name' => 'Samsung', 'parent_id' => 1065,),
array('id' => 1070, 'name' => 'Apple', 'parent_id' => 1065,),
array('id' => 1072, 'name' => 'Apple', 'parent_id' => 1066,),
array('id' => 1075, 'name' => 'Tablets', 'parent_id' => 0,),
array('id' => 1076, 'name' => 'Samsung', 'parent_id' => 1066,),
array('id' => 1077, 'name' => 'All Brands', 'parent_id' => 1075,),
array('id' => 1078, 'name' => 'Samsung', 'parent_id' => 1077,),
array('id' => 1079, 'name' => 'Protector', 'parent_id' => 256,),
array('id' => 1080, 'name' => 'Power', 'parent_id' => 256,),
array('id' => 1081, 'name' => 'Cable', 'parent_id' => 256,),
array('id' => 1082, 'name' => 'Memory', 'parent_id' => 256,),
);
This is the code I categorized:
function quote_make_tree($list,$deep=1, $root = 0)
{
$tree = $packData = [];
foreach ($list as $row) {
$packData[$row['id']] = $row;
}
foreach ($packData as $key => $val) {
if ($val['parent_id'] == $root) {
$tree[] = &$packData[$key];
} else {
$packData[$val['parent_id']]['children'][] = &$packData[$key];
}
}
return $tree;
}
I want to add a deep parameter $deep to quote_make_tree to control the depth of classification.
The result I want:
If $deep = 1 Get only data with parent_id = 0:
$one = array(
0 => array('id' => 3, 'name' => 'Phones', 'parent_id' => 0,),
1 => array('id' => 256, 'name' => 'Accessories', 'parent_id' => 0,),
2 => array('id' => 308, 'name' => 'Appliances', 'parent_id' => 0,),
3 => array('id' => 1057, 'name' => 'Smart', 'parent_id' => 0,),
4 => array('id' => 1075, 'name' => 'Tablets', 'parent_id' => 0,),
);
If $deep = 2,Get level 2 classification below level 1 classification,if $deep=3,Get all 1,2,3 classifications
I have tried get all the data first, then delete the data according to $deep.here is demo,thanks folks
This might be easier to solve using a recursive method. This allows you to check the depth and if you want more details then it will call itself to add in more layers. Each time calling itself you just take one off the depth...
function quote_make_tree($list, $deep=1, $root = 0) {
$output = [];
foreach ( $list as $listItem ) {
if ( $listItem['parent_id'] == $root ) {
if ( $deep > 1 ) {
$listItem['children'] = quote_make_tree($list, $deep-1, $listItem['id']);
}
$output[] = $listItem;
}
}
return $output;
}

Searching array from multidimensional by value

I have an array, what Is like this:
$itemx=
[
'Weapons'=>[
'Sword'=> [
'ID' => '1',
'Name' => 'Lurker',
'Value' => '12',
'Made' => 'Acient'
],
'Shield'=> [
'ID' => '2',
'Name' => 'Obi',
'Value' => '22',
'Made' => 'Acient'
],
'Warhammer'=> [
'ID' => '3',
'Name' => 'Clotch',
'Value' => '124',
'Made' => 'Acient'
]
],
'Drinks'=>[
'Water'=> [
'ID' => '4',
'Name' => 'Clean-water',
'Value' => '1',
'Made' => 'Acient'
],
'Wine'=> [
'ID' => '5',
'Name' => 'Soff',
'Value' => '5',
'Made' => 'Acient'
],
'Vodka'=> [
'ID' => '6',
'Name' => 'Laudur',
'Value' => '7',
'Made' => 'Acient'
]
]
];
I want to find an array from it by Name or ID, so my output should be like this.
*Search by ID=4*
'Water'=> [
'ID' => '4',
'Name' => 'Clean-water',
'Value' => '1',
'Made' => 'Acient'
]
I look at other topics and found that I should use array_search
But It didn't work. I tried like this:
$arra=$itemx["Drinks"];
$key = array_search(4, array_column($arra, 'ID'));
var_dump($arra[$key]);
It also dident work when I tried with Name as a search key.
How can I get this working?
You can do it like below:-
$search_id = 4;
$final_array = [];
foreach($itemx as $key=>$val){
foreach($val as $k=>$v){
if($v['ID'] == $search_id){
$final_array[$k] = $itemx[$key][$k];
}
}
}
print_r($final_array);
https://eval.in/852123
This should probably get you what you want.
function rec($itemx,$search=4){
foreach ($itemx as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
if ($v['ID'] == $search) {
return $value;
}
}
}
}
}
print_r(rec($itemx,4));

Nesting an array based on parent IDs

I've been stuck trying to figure this out for a week now. I have an array in the following format:
[
1 => [
'name' => 'Maths',
'parent_category_id' => NULL
],
2 => [
'name' => 'Algebra',
'parent_category_id' => 1
],
3 => [
'name' => 'Expanding brackets',
'parent_category_id' => 2
],
4 => [
'name' => 'Factorising brackets',
'parent_category_id' => 2
],
5 => [
'name' => 'English',
'parent_category_id' => NULL
],
6 => [
'name' => 'Shakespeare',
'parent_category_id' => 5
]
]
and I want to transform it into an array in this format:
[
'Maths' => [
'category_id' => 1,
'questions' => [], //This array will then be filled with questions regarding each of the categories
'children_categories' => [
'Algebra' => [
'category_id' => 2,
'questions' => [],
'children_categories' => [
'Expanding brackets' => [
'category_id' => 3,
'questions' => [],
'children_categories' => []
],
'Factorising brackets' => [
'category_id' => 4,
'questions' => [],
'children_categories' => []
]
]
]
]
],
'English' => [
'category_id' => 5,
'questions' => [],
'children_categories' => [
'Shakespeare' => [
'category_id' => 6,
'questions' => [],
'children_categories' => []
]
]
]
]
So far I've been able to format categories that have no parents, but I for the life of me cannot figure out how to insert a category that has a parent into that parent's children_categories[] array. Here's the code I'm using, I need help figuring out what I should put in the "else" part of the foreach()
foreach($ids_as_keys as $category_id => $info){ //$info contains the name of the category, and the parent's ID (NULL if there is no parent)
if(is_null($info['parent_category_id'])){ //There is no parent, so put it at the root of $nested
$nested[$info['name']] = [
'category_id' => $category_id,
'questions' => [],
'children_categories' => []
];
}else{ //There is a parent, so search through all items (including sub-arrays, sub-sub-arrays etc.) until we find a match for the parent_category_id, and then add it into the children_categories[] array
}
}
return $nested;
I tested this, absolutely works :
$arr = array(
1 => array(
'name' => 'Maths',
'parent_category_id' => NULL
),
2 => array(
'name' => 'Algebra',
'parent_category_id' => 1
),
3 => array(
'name' => 'Expanding brackets',
'parent_category_id' => 2
),
4 => array(
'name' => 'Factorising brackets',
'parent_category_id' => 2
),
5 => array(
'name' => 'English',
'parent_category_id' => NULL
),
6 => array(
'name' => 'Shakespeare',
'parent_category_id' => 5
)
);
foreach ($arr as $key => &$value) {
if ($value['parent_category_id']) {
$arr[$value['parent_category_id']]['children_categories'][] = &$value;
}
else{
$parents[]=$key;
}
}
$result = array();
foreach ($parents as $val) {
$result[$val] = $arr[$val];
}
print_r($result);
This answer is too close may helpful for you
<?php
$array = [
1 => [
'name' => 'Maths',
'parent_category_id' => NULL
],
2 => [
'name' => 'Algebra',
'parent_category_id' => 1
],
3 => [
'name' => 'Expanding brackets',
'parent_category_id' => 2
],
4 => [
'name' => 'Factorising brackets',
'parent_category_id' => 2
],
5 => [
'name' => 'English',
'parent_category_id' => NULL
],
6 => [
'name' => 'Shakespeare',
'parent_category_id' => 5
]
];
//data array
$data = array();
$i = 0;
//gothrough one by one
foreach($array as $key=>$value)
{
//set the parent array
if(is_null($value['parent_category_id']))
{
$data[$value['name']]= array();
$data[$value['name']]['category_id'] = $key;
$data[$value['name']]['questions'] = array();
$data[$value['name']]['children_categories'] = array();
//add the childrens according to the parent
}elseif(array_key_exists($value['parent_category_id'], $array)){
//find the parent
$parent = $array[$value['parent_category_id']];
$data[$parent['name']]['children_categories'][$value['name']] = array();
$data[$parent['name']]['children_categories'][$value['name']]['category_id'] = $key;
$data[$parent['name']]['children_categories'][$value['name']]['questions'] = array();
}
}
//display the result
print_r($data);
Try using recursive function.
function insert_child($curArr,$childArray,&$parentArray){
foreach($parentArray as $key=>&$val){
if(is_array($val) && sizeof($val) > 0 ){
if($val['category_id']==$curArr['parent_category_id']){
$val['children_categories'][$curArr['name']] = $childArray;
return TRUE;
}else{
insert_child($curArr,$childArray,$val['children_categories']);
}
}
}
return FALSE;
}
Where $nest is your input array
$nest = array(
1=>array(
'name' => 'Maths',
'parent_category_id' => NULL
),
2=>array(
'name' => 'Algebra',
'parent_category_id' => 1
),
3=>array(
'name' => 'Expanding brackets',
'parent_category_id' => 2
),
4=>array(
'name' => 'Factorising brackets',
'parent_category_id' => 2
),
5=>array(
'name' => 'English',
'parent_category_id' => NULL
),
6=>array(
'name' => 'Shakespeare',
'parent_category_id' => 5
),
);
code
$result=array();
foreach($nest as $key=>$val){
$temp = array(
'category_id'=>$key,
'questions'=>array(),
'children_categories'=>array(),
);
if(!in_array($val['name'],$result) && $val['parent_category_id']==NULL){
$result[$val['name']] = $temp;
}else{
insert_child($val,$temp,$result);
}
}
echo "<pre>";
print_r($result);
exit();
PHPFIddle here

Categories