how to add an item to array in laravel - php

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;

Related

Filter Array based on if contains php

My aim here is to remove the whole object from the array if "record_type" is null. I should then only be left with data that has a record_type set in the array.
I've looked into the array filter not sure how I target the data within the array "record_type". My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null) in the array
Solution: use array_filter() on your source array ($arr) and filter for records with 'record_type' != "NS" (assuming "NS" is what you refer to as null, or not set).
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
working demo
EDIT
If you want to filter for only those records that are of a certain type, e.g. type 'record', following should help:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
working demo
If your Goal is to filter array to remove any inner-array that hasn't a record_type, So use array_filter with a callback function fn to check that record_type exist with isset function.
array_filter($arr, fn($el)=>isset($el["record_type"]));

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 do I solve 'Undefined index' error when the key exists?

"foreach" loop results in an 'Undefined Index' error when I manipulate an array.
The array is generated from MS Excel and works fine with PHP array functions. When I use "foreach" loop to extract data, I get the 'Undefined Index' error but when I dump the value of the index, I get desired results.
The code extract is as below:
foreach ($membership_data as $data){
//dd($data["Gender"]);
if($data["Gender"]=='Male') {
$males_dates_of_birth[] = $data['DateofBirth'];
} elseif ($data["Gender"]=='Female'){
$females_dates_of_birth[] = $data['DateofBirth'];
} else {
$erroneous_gender_dates_of_birth[] = $data['DateofBirth'];
}
}
How can this be solved?
Or else, is there a better way to get three arrays containing dates of birth for various genders? The sample data array is as below.
array:100 [▼
6 => array:15 [▼
"MemberNumber" => "48490"
"Surname" => "Wuckert"
"FirstName" => "Clement"
"OtherNames" => "Dr. Monique Murazik II"
"DateofBirth" => "1968-08-4"
"DateEmployed" => "1988-08-04"
"DateJoinedScheme" => "1968-08-4"
"Gender" => "Female"
"DocumentType" => "National ID"
"DocumentNumber" => "a370523307a"
"KRAPIN" => "a459831176c"
"NSSFNumber" => "a526026924k"
"TelephoneNumber" => "722136702"
"EmailAddress" => "annie99#yahoo.com"
"TelephoneNumberCountry" => "Kenya"
]
7 => array:15 [▶]
8 => array:15 [▶]
9 => array:15 [▶]
10 => array:15 [▶]
11 => array:14 [▶]
You need to check if the key is existing in the array or not using array_key_exists
if(array_key_exists('Gender', $data) && $data["Gender"]=='Male') {
$males_dates_of_birth[] = array_key_exists('DateofBirth', $data) ? $data['DateofBirth'] : '';
} elseif (array_key_exists('Gender', $data) && $data["Gender"]=='Female'){
$females_dates_of_birth[] = array_key_exists('DateofBirth', $data) ? $data['DateofBirth'] : '';
} else {
$erroneous_gender_dates_of_birth[] = array_key_exists('DateofBirth', $data) ? $data['DateofBirth'] : '';
}

PHP Laravel Foreach trough multi array

I have the following multi dimension array and I am not able to do a foreach loop (with laravel). I want to show the name.
Any idea how to loop trough that array to show just the name? I reduced the showed array -> ...
I want to loop trough that array not in a view but in a controller because i want to create a database entry for every client
array:1 [▼
"client" => array:52 [▼
0 => array:11 [▼
"name" => "Company One"
...
]
1 => array:11 [▼
"name" => "Company 2"
...
]
Thanks for your help.
$array = [
'client' => [
[
'name' => 'Company One',
'foo' => 'Foo One',
],[
'name' => 'Company 2',
'foo' => 'Foo 2',
]
]
];
$names = array_pluck($array['client'], 'name');
foreach($names as $name) {
echo $name; // Replace this with the logic to create DB entry
}
Its easy all you have to do is this ,lets assume that your array are in the varibale $myArray
$myArray = [▼
"client" => array:52 [▼
0 => array:11 [▼
"name" => "Company One"
...
]
1 => array:11 [▼
"name" => "Company 2"
...
]
then you have to do:
#foreach ($myArray->client as $data)
{{$data->name}}
#endforeach

Laravel collection contains

I'm using the Laravel contains method on a collection https://laravel.com/docs/5.3/collections#method-contains. But it does not work for me.
foreach ($this->options as $option) {
if($options->contains($option->id)) {
dd('test');
}
}
dd($options); looks like this:
Collection {#390
#items: array:1 [
0 => array:3 [
0 => array:7 [
"id" => 10
"slug" => "test"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
1 => array:7 [
"id" => 11
"slug" => "test-1"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
2 => array:7 [
"id" => 12
"slug" => "test-2"
"name" => "test"
"poll_id" => 4
"created_at" => "2016-11-12 20:42:42"
"updated_at" => "2016-11-12 20:42:42"
"votes" => []
]
]
]
}
Result of dd($option->id); is 10.
What could be wrong? Or is there a better way?
You should pass a key / value pair to the contains method, which will
determine if the given pair exists in the collection. Use contains() method in this way:
foreach ($this->options as $option) {
// Pass key inside contains method
if($option->contains('id', $option->id)) {
dd('test');
}
}
Use the following, which tells Laravel you want to match the 'id':
$options->contains('id', $option->id);
Docs
foreach ($this->options as $option) {
if(!$options->flatten(1)->where('id',$option->id)->isEmpty()) {
dd('test');
}
}
The contains method determines whether the collection contains a given item.
There are basically three ways in which it can be used :
simply checking the item
$collection = collect(['name' => 'Sarah', 'age' => 23]);
$collection->contains('Desk');
// false
$collection->contains('Sarah');
// true
checking the key/value pair :
$collection = collect([
['name' => 'Sarah', 'age' => 23],
['name' => 'Vicky', 'age' => 34],
]);
$collection->contains('name', 'Hank');
// false
checking via callback function :
$collection = collect([3, 5, 7, 9, 11]);
$collection->contains(function ($value, $key) {
return $value < 2;
});
// false
Now, for your problem, we will use the second category, i.e :
foreach ($this->options as $option) {
// here id is key and $option->id is value
if($option->contains('id', $option->id)) {
dd('test');
}
}
Link to docs

Categories