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

$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

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

Searching string nested array - 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);

How to acess the object inside the nested array in laravel

I am new to laravel. I have an array called data which is fetching the data as a form of nested array. Its structure looks like this.
array:1 [▼
0 => array:2 [▼
0 => {#3 ▼
+"id": "8"
+"title": "Accounting"
+"type": {
+"id": "18"
+"title": "BookKeeping"
}
}
1 => {#3 ▼
+"id": "10"
+"title": "Accounting"
+"type": {
+"id": "20"
+"title": "Balancesheet"}
}
]
]
This is the data that I am getting in the form of a nested array. I need to find a maximum id i.e. 10 so that I can get the associated type title based on the max id. I tried in several ways by using array helpers, and using foreach loop but could not succeed.Any kind of help and support is appreciated. Hope to get a positive rep
you can use foreach.
$array = <your array variable>;
$max = 0;
foreach($array as $value) if($value['id'] > $max) $max = $value['id'];
or if you want get key of this variable
$array = <your array variable>;
$max = 0;
foreach($array as $key => $value) if($value['id'] > $max) $max = $key;
or if your array is in ascending order you can just get your last elements' id like this:
$array = <your array variable>;
$max = array_pop($array)['id'];
note: but if you use array_pop you lost last element - https://www.php.net/manual/en/function.array-pop.php
and there is way to not lost
$array = <your array variable>;
$max = end($array)['id'];

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);

PHP if in_array() how to get the key as well?

Struggling with a tiny problem.
I have an array:
Array
(
[0] =>
[6] => 6
[3] => 5
[2] => 7
)
I am checking if a set value is in the array.
if(in_array(5, $array)) {
//do something
} else {
// do something else
}
The thing is, when it find the value 5 in array, I really need the key to work with in my "do something".
In this case I need to set:
$key = 3;
(key from the found value in_array).
Any suggestions?
array_search() is what you are looking for.
if (false !== $key = array_search(5, $array)) {
// found!
} else {
// not found!
}
If you only need the key of the first match, use array_search():
$key = array_search(5, $array);
if ($key !== false) {
// Found...
}
If you need the keys of all entries that match a specific value, use array_keys():
$keys = array_keys($array, 5);
if (count($keys) > 0) {
// At least one match...
}
You could just use this http://www.php.net/manual/en/function.array-search.php
$key = array_search(5, $array)
if ($key !== false) {
...
You can try
if(in_array(5, $array))
{
$key = array_search(5, $array);
echo $key;
}
this way you know it exists, and if it doesn't it doesn't cause notices, warnings, or fatal script errors depending on what your doing with that key there after.
Maybe you want to use array_search instead, which returns false if the value is not found and the index if the value is found. Check out the description here
In case anyone need it in array of arrrays. My case was this:
I had an array like this:
$myArray =
array:3 [▼
0 => array:3 [▼
0 => 2
1 => 0
2 => "2019-07-21 23:59:59"
]
1 => array:3 [▼
0 => 3
1 => 2
2 => "2019-07-21 23:59:59"
]
2 => array:3 [▼
0 => 1
1 => 1
2 => "2019-07-21 23:59:59"
]
]
And another one like this (an array of objects):
$Array2 =
Collection {#771 ▼
#items: array:12 [▼
0 => {#1047 ▼
+"id": 2
+"name": "demografico"
+"dict_key": "demographic"
+"component": "Demographic"
+"country_id": null
+"created_at": null
+"updated_at": null
}
1 => {#1041 ▶}
2 => {#1040 ▶}
etc...
As the OP, I had to "do something" (use values in a html php template, my case Laravel with blade) with the key where some value was in the array. For my code, I had to use this:
foreach($Array2 as $key => $item)
if(false !== $key = array_search($item->id, array_column($myArray, 0))
// Note that $key is overwritten
<input type="number" class="form-control" id="{!! $item->id !!}" value="{{ $myArray[$key][1] }}">

Categories