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));
Related
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>';
}
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.
I have a json. First i have to decode then add loop on a specific key of json.
public function saveRecode() {
$json ='{"productID":"1","productPrice":"5585.00","productDetails":{"productImage":"https:\/\/development.modeconfigurator.com\/eCommerce\/backdrop.jpg","TABLE TOP":"COPPER DISTRESSED","TABLE FRAME":"RAL 5024 PASTEL BLUE"},"_":"1583172411557"}';
$jsonDecode = json_decode($json, true);
foreach ($jsonDecode["productDetails"] as $key => $value) {
$options = [
'0' => [
'sort_order' => '1',
'title' => $key,
'price_type' => 'fixed',
'price' => '',
'type' => 'drop_down',
'is_require' => '0',
'values' => [
'0' =>[
'title' => $value,
'price' => '',
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '0',
'is_delete' => '0',
]
]
]
];
}
foreach ($options as $arrayOption) {
$this->_logger->debug("enter in opt ");
$this->_logger->info(print_r($arrayOption,true));
$option = $this->_options
->setProductId($_product->getId())
->setStoreId($_product->getStoreId())
->addData($arrayOption);
$option->save();
$_product->addOption($option);
}
}
In database only last recode save. But i want to save all parameters please take a loop.
You're replacing $options each time through the loop, not adding a new element to it. It should be:
$options = [];
foreach ($jsonDecode["productDetails"] as $key => $value) {
$options[] = [
'sort_order' => '1',
'title' => $key,
'price_type' => 'fixed',
'price' => '',
'type' => 'drop_down',
'is_require' => '0',
'values' => [
'0' =>[
'title' => $value,
'price' => '',
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '0',
'is_delete' => '0',
]
]
];
}
$lang = [
'en' => ['id'=>'1', 'name' => 'English', 'short' => '1', 'active' => '1',],
'tn' => ['id'=>'2', 'name' => 'Tamil', 'short' => '2', 'active' =>'1',],
]; // sample array`
In yii2 i can use the array map method as follow.
ArrayHelper::map($lang,'id','name');
But how to put the array index ('en' and 'tn') in the place 'id'
ex:ArrayHelper::map($lang, array_index,'name');
thanks
This is not a function of ArrayHelper as far as i know, but can't you just make your own? Give something like this a shot:
function YourArrayHelper($arr)
{
$returnArr = [];
foreach($arr as $key => $value)
{
$returnArr[$key] = $value['name'];
}
return $returnArr;
}
$types = [
'en' => ['id'=>'1', 'name' => 'Sell', 'short' => '1', 'active' => '1',],
'tn' => ['id'=>'2', 'name' => 'buy','short' => '2', 'active' =>'1',],
]; // sample array
var_dump(ArrayHelper::map($types,'id','name'));
echo '<br>';
var_dump(YourArrayHelper($types));
I have an complicated array that looks like this:
$input=array(
(int) 0 => array(
'XXX' => array(
'id' => '7',
'p_id' => '1',
'address' => '9463',
'arrival_time' => '2014-05-01 03:30:00'
),
'YYY' => array(
'id' => '1',
'iden' => '1111',
'name' => 'Tom'
)
),
(int) 1 => array(
'XXX' => array(
'id' => '9',
'p_id' => '2',
'address' => '9469',
'arrival_time' => '2014-05-27 16:43:58'
),
'YYY' => array(
'id' => '2',
'iden' => '2222',
'name' => 'Sam'
)
),
(int) 2 => array(
'XXX' => array(
'id' => '3',
'p_id' => '3',
'address' => '9462',
'arrival_time' => '2014-04-21 14:05:00'
),
'YYY' => array(
'id' => '3',
'iden' => '3333',
'name' => 'James'
)
)
)
I would like to convert it such that it looks like this;
$output=array(
(int) 0 => array(
'name' => 'Tom',
'iden' => '1111',
'address' => '9463'
),
(int) 1 => array(
'name' => 'Sam',
'iden' => '2222',
'address' => '9469'
),
(int) 2 => array(
'name' => 'James',
'iden' => '3333',
'address' => '9462'
)
I wrote some code to solve this problem:
foreach ( $input as $key => $value)
{
$output['name']=$input[$key]['YYY']['name'];
$output['iden']=$input[$key]['YYY']['iden'];
$output['address']=$input[$key]['XXX']['address'];
}
Unfortunately, it retrieves only the last element of the input array.
Can someone more experienced help?
Thank you very much.
You are overwriting the values in each iteration, as you always write to $output['name'] etc.
foreach ( $input as $key => $value)
{
$output[$key] = array(
'name' => $value['YYY']['name'],
'iden' => $value['YYY']['iden'],
'address' => $value['XXX']['address']
);
}
The key here is using $output[$key] instead of $output - this way you will add a new element in each iteration.
Also $input[$key] and $value are equivalent, so I used the shorter variant ;)
Try this in your foreach loop :-
foreach ( $input as $key=>$value)
{
$output[$key]['name']=$value['YYY']['name'];
$output[$key]['iden']=$value['YYY']['iden'];
$output[$key]['address']=$value['XXX']['address'];
}
You have to add an index to the array in the foreach: $output[$key]["name"] = ...;