Add key and value to array if it doesnt exist - php

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

Related

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

Insert multiple items in Laravel Collection inside a php loop

Hi I am trying to insert multiple items into a laravel collection inside a php loop but only one is getting inserted (the last one), please help to insert all the values.
This array $some_array = array(); has values like 1,2,3,4
The loop is like
foreach ($some_array as $key => $value) {
$final_lists = collect([
(object) [
'customer_id' => $value,
],
]);
}
Output required
"final_lists": [
{
"customer_id": 4,
"name": "Name 1",
},
{
"customer_id": 2,
"name": "Name 2",
},
]
use collection class at the top of the page.as,
use Illuminate\Support\Collection;
$collection = new Collection;
foreach([1,2,3,4] as $item) {
$collection->push((object)[
'customer_id' => $item,
'name' => 'demostring'.$item
]);
}
dd($collection->all());
use this snippet. Let me know the results.
If you require a list of multiple collections, you can append a new collection to an array like:
$a = [1,2,3,4,5]; // Your Array
$requiredList = [];
foreach($a as $key => $value){
$requiredList[] = (object)[
'customer_id' => $value,
'name' => 'Customer Name: ' . $value
];
}
dd($requiredList);
It will provide the desired list like:
^ array:5 [▼
0 => {#3971 ▼
+"customer_id": 1
+"name": "Name1"
}
1 => {#3207 ▼
+"customer_id": 2
+"name": "Name2"
}
2 => {#3977 ▼
+"customer_id": 3
+"name": "Name3"
}
3 => {#3961 ▼
+"customer_id": 4
+"name": "Name4"
}
4 => {#3956 ▼
+"customer_id": 5
+"name": "Name5"
}
]

Undefined index error while key exists in array

I'm pulling my hair on a proble which seems very simple, but I can't find a solution.
I have a simple $row array here :
array:2 [▼
"reference" => "ABCDEF"
"quantity" => "10"
]
I'm trying to parse it and retrieve quantities per reference using :
$line = [
'ref' => strtoupper($row["reference"]),
'quantity' => $row["quantity"]
];
I'm looping through array of lines using this code:
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
As a test, my main array $rows has 2 lines :
^ array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
1 => array:2 [▼
0 => "WXCVBN"
1 => "3"
]
2 => array:1 [▼
0 => null
]
]
However, I'm getting the following error :
Undefined index: reference
Strangely enough, if I comment out the
'ref' => strtoupper($row["reference"]),
line, I can get the "quantity" value with no issue...
I know the key is in there, since the debug of the $row object gives the above result.
It must be dead simple... but I can't find the solution...
If anyone could please help ?
So apparently the $row variable a row from a bigger array that is used in a foreach loop.
This might be the solution to your problem.
$array = [
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
];
$line[] = '';
foreach($array as $row)
{
$line['ref'] = $row['reference'];
$line['quantity'] = $row['quantity'];
}
In this example $array is your bigger array, i use it to test the example.
After that i create a empty array $line to append the "new" data.
Could you try this?
Edit:
After taking a look at your loop and the array i noticed that your array doesnt have a reference key. Can you try strtoupper(row[0])?
Viewing your code seems that you convert $row array to $line without rewrite key in new array.
your code
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
With your rewrite you can access $line data by index, not by key
array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
...
]
My solution
If you want to access your $line data by key, you need to rewrite your loop as:
foreach($rows as $rowData) {
foreach($rowData as $rowKey => $rowValue) {
$data = [
'ref' => $rowKey => strtoupper$($rowValue),
'quantity' => $row['quantity']
];
}
$line[] = $data;
}

How to access the array inside the array

I don't know why I can't figure this out.
In my controller, how can I loop through this array and only get the values for name and url.
both of those values will be passed to insert a new record.
array:3 [▼
0 => array:2 [▼
"name" => "Discogs"
"url" => "https://www.discogs.com/artist/267549"
]
1 => "2"
2 => array:2 [▼
"name" => "Official homepage"
"url" => "http://www.blackmetal.com/~mega/TBD/"
]
]
You can do with this code:
foreach ($array as $value) {
if (is_array($value) && isset($value['name']) && isset($value['url'])) {
// Do whatever you want
}
}
You can try utilising Laravel's collection for this...
$items = collect($array)
->filter(function($item) {
return is_array($item);
});
If you have extra attributes to the ones you listed then you can use map() to for this:
$items = collect($array)
->filter(function($item) {
return is_array($item);
})
->map(function($item) {
return Arr::only($item, [
'name',
'url',
];
});
p.s. don't forget to add use Illuminate\Support\Arr; to use Arr

How to loop through json data php

I'm trying to loop through JSON data in php.
array:2 [
"cart" => array:3 [
0 => array:4 [
"id" => 3
"name" => "ying"
"price" => "4000"
]
1 => array:4 [
"id" => 2
"name" => "yang"
"price" => "4000"
]
2 => array:4 [
"id" => 4
"name" => "foo"
"price" => "5000"
]
]
"total" => 13000
]
I've used the json_decode function and a foreach over the data.
foreach (json_decode($arr) as $item) {
$item['name'];
}
I want to be able to get each "cart" item and the single "total" data but I keep getting an illegal offset error when i try to call things like $item['name']
As written in json_decode doc:
Note: When TRUE, returned objects will be converted into associative arrays.
If you dont pass 2nd argument as true then it will be treated as object as below.
$arr = json_decode($arr);
$names = [];
foreach ($arr->cart as $item) {
$names[] = $item->name;
}
echo $arr->total;// this is how you will get total.
If you pass 2nd argument as true then it will be treated as associative array as below.
$names = [];
$arr = json_decode($arr, true);
foreach ($arr['cart'] as $item) {
$names[] = $item['name'];
}
echo $arr['total'];// this is how you will get total.
In your code, your data is having two main keys viz. cart and total. From which, you are trying to fetch the data of cart which I specified in my answer.

Categories