Searching string nested array - PHP - php

I have a question regarding nested array
dd($this->forest);
it give me this:
array:2 [▼
0 => array:3 [▼
"id" => 12
"location" => 'east'
"type" => 'reservation'
]
1 => array:3 [▼
"id" => 13
"location" => 'west'
"type" => 'rainforest'
]
2 => array:3 [▼
"id" => 14
"location" => 'north'
"type" => 'rainforest'
]
]
so I want to search 'swamp' and 'mangrove' like "type" => 'swamp' or "type" => 'mangrove' but these type is not in the array of $this->forest. So, I have used in_array to sort it out.
$this->typeOfForest = '';
foreach($this->forest as $item){
if(!in_array('swamp', $item)){
$this->typeOfForest = 'swamp_not_found';
break;
}
elseif(!in_array('mangrove', $item)){
$this->typeOfForest = 'mangrove_not_found';
break;
}
}
dd($this->typeOfForest);
but when I dd($this->typeOfForest);
it will not set as $this->typeOfForest = 'swamp_not_found'; instead $this->typeOfForest = 'mangrove_not_found';
Also, when I insert new data 'swamp' into array $this->forest; and run again in_array function it will give me $this->typeOfForest = 'swamp_not_found'; instead of $this->typeOfForest = 'mangrove_not_found';
Thank you!

As said in the comments, the in_array function does not work with a multidimensional array. You need to use the array_column function to get all the types and then just do a lookup.
$this->typeOfForest = null;
$types = array_column($this->forest,'type');
if(in_array('swamp', $types)){
$typeOfForest = 'swamp found';
}elseif(in_array('mangrove', $types)){
$typeOfForest = 'mangrove found';
}
var_dump($this->typeOfForest);

You are using in_array function, it just searches for a given value in every index of the array, But as you have a 2D array, So in_array cant find any index with value JUST 'swamp', so your first IF condition becomes TRUE.
You can do like this:
$this->typeOfForest = '';
foreach($this->forest as $item){
if ($item['type'] == 'swamp'){
$typeOfForest='swamp found';
break;
}
elseif($item['type'] == 'mangrove'){
$typeOfForest='mangrove found';
break;
}
}
var_dump($this->typeOfForest);

Related

convert array of arrays into comma separated list with unique values - PHP

I have an array that looks like below:
$var[] = ^ array:4 [▼
0 => array:1 [▼
0 => "apple"
]
1 => array:1 [▼
0 => "apple"
1 => "grape"
]
2 => array:1 [▼
0 => "orange"
]
3 => array:1 [▼
0 => "banana"
]
]
Is there a way to convert this array into comma separated list with unique values as below?
$var = "apple,grape,orange,banana"
I tried implode(', ',$var) but it's not working as expected. Any help pls?
Update: My sub-array may have more than 1 element. It's dynamic.
This produces the results given the expected input. Basically array_column get's the first item from each item of the array (0 based). Then array_unique on that will simply get the values without duplicates.
$arr = [
['apple'],
['apple'],
['banana'],
['pie'],
];
print_r(array_unique(array_column($arr, 0)));
EDIT: since there might be more than one item in the inner arrays, there's no shame in doing a non one-liner solution:
$result = [];
foreach ($arr as $row) {
foreach ($row as $item) {
if (array_search($item, $result) === false) {
$result[] = $item;
}
}
}
print_r($result);
There's also a one-liner solution:
$result= array_unique(call_user_func_array('array_merge', $arr));
cf. https://stackoverflow.com/a/14972714/13720553

how to add an item to array in laravel

i have a function that it fills the one array like below :
if (isset($options[$attribute->id][$optionId])) {
foreach ($options[$attribute->id][$optionId] as $item) {
. . . .
$attributeOptionsData[] = [
'id' => $optionId,
'label' => $attributeOption->label ? $attributeOption->label : $attributeOption->admin_name,
'swatch_value' => $attribute->swatch_type == 'image' ? $attributeOption->swatch_value_url : $attributeOption->swatch_value,
'products' => $options[$attribute->id][$optionId],
'images' => $productImage ?? null,
];
dd($attributeOptionsData);
}
the result of this dd is like below :
array:1 [▼
0 => array:5 [▼
"id" => 1
"label" => "black"
"swatch_value" => "#000000"
"products" => array:1 [▶]
"images" => "product/4618/rAkC2aC3QJB6kMiAAzIGk6nUzGHxpdfIS55g3T0P.jpeg"
]
]
now what i want to do is that after the last line add some content to this array and make it like below:
array:1 [▼
0 => array:5 [▼
"id" => 1
"label" => "مشکی"
"swatch_value" => "#000000"
"products" => array:1 [▶]
"images" => "product/4618/rAkC2aC3QJB6kMiAAzIGk6nUzGHxpdfIS55g3T0P.jpeg"
"custom_field" => "some value"
]
]
on the line that i dd the array i want add the customfield to it . how can i do that thanks in advance.
the reason i dont insert like others in that i want to add the custom field in a foreach loop based on 1 field of that array
So, if you simply want to add something at the bottom of an array, just use array_push().
In your case, you would need to retrieve the whole $attributeOptionsData[] in a foreach loop and append the array to the key you're in, during that loop. Be aware that this is somehow inefficient. If you want to add a line based on a value you can retrieve in the first foreach loop, you could've just made an if-statement asking for that value and add it with array_push() afterwards.
Either way, I think this is what you're looking for:
if (isset($options[$attribute->id][$optionId])) {
foreach ($options[$attribute->id][$optionId] as $item) {
$attributeOptionsData[] = [
'id' => $optionId,
'label' => $attributeOption->label ? $attributeOption->label : $attributeOption->admin_name,
'swatch_value' => $attribute->swatch_type == 'image' ? $attributeOption->swatch_value_url : $attributeOption->swatch_value,
'products' => $options[$attribute->id][$optionId],
'images' => $productImage ?? null,
];
}
foreach($attributeOptionsData as $key=>$data){
array_push($attributeOptionsData[$key], ["custom_field" => "some value"])
}
}
$attributeOptionsData is an associative array. You can assign values to it by specifying the array $key:
$attributeOptionsData[$key] = $value;

PHP - How to get "upper" key from value in a nested array?

$arrayTypesAndSubtypes = Account::getTypesAndSubtypes();
$subtype = $request->input('subtype');
Here's a dd of $arrayTypesAndSubtypes from which I want to get the "upper (?) key" for a given value.
array:2 [▼
"REVENUE" => array:1 [▼
0 => "REVENUE"
]
"ASSET" => array:1 [▼
0 => "BANK_ACCOUNT"
]
]
Here, the following returns false (because Array_search() will return 0 for either REVENUE or BANK_ACCOUNT ; however, what I'm looking for is to return either REVENUE or ASSET (what I'm calling the "upper key" - is there a more proper term for that?).
Any help would be appreciated!
Assuming they are in the 0 key, just extract that column, combine with the current keys and search:
$key = array_search('BANK_ACCOUNT', array_combine(array_keys($array),
array_column($array, 0)));
var_dump(key); //should return ASSET
Or if you have multiple under each key, then loop:
$key = false;
foreach($array as $key => $values) {
if(array_search('BANK_ACCOUNT', $values)) { // or in_array('BANK_ACCOUNT', $values)
break;
}
}
var_dump($key); //should return ASSET
As an alternative, you could "flatten" your array first using array_map:
$flattened = array_map(fn(array $val) => $val[0], $arr));
Then simply array_search it:
$key = array_search('BANK_ACCOUNT', $flattened); // ASSET

How to push into an array and not reset index PHP

I have and array and i need to push a value into the first index(0).
array:3 [▼
4 => "test1"
5 => "test2"
6 => "test3"
]
I need the indexes to stay like this, so the array will become like below. Since the indexes are the IDS of the values.
array:3 [▼
0 => "None selected"
4 => "test1"
5 => "test2"
6 => "test3"
]
To populate array:
$accuGroups = UpselGroup::where('accu_group','1')->with('UpselProducts.products')->pluck('naam','id')->toArray();
What i tried:
$accuGroups = array_merge([0 => 'None selected'], $accuGroups);
outcome (not what i want):
array:4 [▼
0 => "None selected"
1 => "test1"
2 => "test2"
3 => "test3"
]
Any help is appreciated
thanks
array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value
so use like this :
$accuGroups[0]="None selected";
Try this
$none_selected = array(
0 => 'None selected');
$accuGroups = $none_selected + $accuGroups;
you can try this
<?php
$queue = array("test1", "test2","test3", "test4");
array_unshift($queue, "None selected");
echo "<pre>";
print_r($queue);
?>
$accuGroups[0]="Not Selected.";
$accuGroups[6]="Not Selected.";
The array will reset its index value with given Value;
Keep another value which you have to merge as array and add it to first array and you will get result.
$a=['4' => "test1", '5' => "test2",'6' => "test3"];
$b=['0'=>'Not Selected'];
$c=$b+$a;
in $c you will get result as per your requirement.
You can try this
<?php
$array = array('4' => 'test1','5' => 'test2', '6' => 'test3');
$add = array('0'=>'None selected');
$final = $add + $array;
echo "<pre>";print_r($final);die;
?>

Add key and value to array if it doesnt exist

So I have an Array called $sales that consits of objects like:
"DR22" => array:3 [▼
"brand" => "DR22"
"year" => "0"
"last_year" => null
]
"FGIPA46C" => array:3 [▼
"brand" => "FGIPA46C"
"month" => "3"
"year" => "3"
]
Now each one should have "Month" "Year" "Last Year" "Last Month" but if there is no sale its not in there, which i get, but if it doesnt exist I just want to add it with 0 value. I tried:
foreach ($sales as $sale)
{
if (empty($sale['month'])) {
$sale['month'] = 0;
}
}
But it doesnt add anything. Spits out the same.
foreach ($sales as &$sale) {if (empty($sale['month'])) { $sale['month'] = 0; }}
You need to pass the $sale array by reference (using the &). This will mean that the original $sales array is updated
Or you can use array_map function, for example:
$array = array_map(function($item){
if(empty($item["month"])){
$item["month"] = 0;
}
return $item;
}, $array);

Categories