I am trying to loop through a multidimensional array in my view.
the array (I am passing $mailchimp from my controller to my view) is:
array:19 [▼
"id" => "f3200e9cc5a900bb7c075103b871232f0"
"email_address" => "john.doe#discworld.com"
"unique_email_id" => "xalasd"
"email_type" => "html"
"status" => "subscribed"
"merge_fields" => array:2 [▼
"FNAME" => "John"
"LNAME" => "Doe"
]
"stats" => array:2 [▶]
"ip_signup" => ""
"timestamp_signup" => ""
"ip_opt" => "93.212.91.32"
"timestamp_opt" => "2016-10-27T13:53:02+00:00"
"member_rating" => 2
"last_changed" => "2016-10-27T13:53:02+00:00"
"language" => ""
"vip" => false
"email_client" => ""
"location" => array:6 [▶]
"list_id" => "76980934492"
"_links" => array:8 [▶]
]
With this Code in my view:
#foreach($mailchimp as $user)
#foreach($user as $key => $value)
<ul>
<li>{{$value}}</li>
</ul>
#endforeach
#endforeach
An exception is thrown: Invalid argument supplied for foreach()
Can somebody tell me how to fix this ?
you are expecting for the value of each of the first array to also be an array. That is not the case, only some values from the first array is an array, so you must put a condition. You can use the is_array helper to see if the value from the first array is an actual array, if so, loop thru each one of those.
foreach($a as $b){
if(is_array($b)){
foreach($b as $c){
echo($c);
}
}
}
As mentioned by Carlos the main issue you're encountering is because you're trying to echo an array find his answer here.
Regarding your second issue Thanks Carlos. It tried you solution with this result: htmlentities() expects parameter 1 to be string, array given do you have any other code on that page, perhaps {{ Form::text('something', $array) }}
Related
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;
"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'] : '';
}
I am doing a request to an API and for each request I get an array with the BrowseNodes back. Inside this array I get this result:
array:1 [
"BrowseNode" => array:3 [
"BrowseNodeId" => "2502033031"
"Name" => "OBD-II Diagnosewerkzeuge"
"Ancestors" => array:1 [
"BrowseNode" => array:3 [
"BrowseNodeId" => "5142250031"
"Name" => "Motorwerkzeuge & Zubehör"
"Ancestors" => array:1 [
"BrowseNode" => array:3 [
"BrowseNodeId" => "2502064031"
"Name" => "Werkzeuge"
"Ancestors" => array:1 [
"BrowseNode" => array:4 [
"BrowseNodeId" => "79899031"
"Name" => "Kategorien"
"IsCategoryRoot" => "1"
"Ancestors" => array:1 [
"BrowseNode" => array:2 [
"BrowseNodeId" => "78191031"
"Name" => "Auto & Motorrad"
]
]
]
]
]
]
]
]
]
]
If this would be a fixed array which always had this length it would be easy for me to get the last BrowseNode Array and the value with the key "Name". In this case it would be the this one "Name" => "Auto & Motorrad".
However, because a category can have one or more nested arrays, it is not static...
That means I have to find a solution to always get the most nested array and from this one the name to get the category. Because it is dynamic data, I don't know how to solve that. I just know I always have to get the BrowseNode and then inside the BrowseNode array. I have to get the Ancestors and inside this Ancestors again. I have to get the BrowseNode array until I arrived at the last BrowseNode array and the get the name.
So, I have to iterate through my array until the BrowseNode array doesn't have an Ancestors array anymore and the get the name of this BrowseNode array.
Do you guys have any idea on how to do this?
I guess you can use recursion to achieve that.
On each object, search for Ancestors, if not found return the name, else do so again on the Ancestors.
Consider the following code:
$arr = array("BrowseNode" => array("BrowseNodeId" => "1", "Ancestors" => array("BrowseNode" => array("BrowseNodeId" => "2", "Ancestors" => array("BrowseNode" => array("BrowseNodeId" => "3"))))));
function getLastName($elem) {
$elem = $elem["BrowseNode"];
if (!array_key_exists("Ancestors", $elem))
return $elem['BrowseNodeId'];
else return getLastName($elem["Ancestors"]);
}
echo getLastName($arr);
Notice that this code return id instead of your Name - small modification I leave to you...
There might be a more "correct" way of doing this but since I'm writing this on my phone on a plane, you'll have to forgive my not being able to proof check my answer. But you could do a recursive function, like...
function recurseArray($browseNode)
{
if(isset($browseNode["Ancestors"])) {
recurseArray($browseNode["Ancestors"]["browseNode"])
} else {
// Do whatever you want with the last iteration
}
}
Hope that makes sense!
I am passing a variable $mailchimp from my Controller to my View.
this is what I got with {{dd($mailchimp)}}
array:8 [▼
"id" => "xyz123"
"email_address" => "john.doe#discworld.com"
"unique_email_id" => "c9a36649c8"
"email_type" => "html"
"status" => "subscribed"
"merge_fields" => array:2 [▼
"FNAME" => "John"
"LNAME" => "Doe"
]
"stats" => array:2 [▼
"avg_open_rate" => 0
"avg_click_rate" => 0
]
"list_id" => "769808qeqw92"
]
how can I loop through this array ($mailchimp) ? With the code below I get an exception: "htmlentities() expects parameter 1 to be string, array given"
#foreach($mailchimp as $user)
#if(is_array($user))
#foreach($user as $key => $value)
{{$value}}
#endforeach
#endif
#endforeach
Update:
With this Code in My Controller
public function index()
{ //Fetch all subscribers from DB
$subscribers = Subscriber::where('user_id', Auth::user()->id)->orderBy('created_at','asc')->get();
foreach ($subscribers as $key => $subscriber) {
//Check if the local subscriber is also present in mailchimp
$mailchimp = Newsletter::getMember($subscriber->email);
}
return view('backend.newsletter.contacts.index')->withSubscribers($subscribers)
->withMailchimp($mailchimp);
}
I need to iterate the mailchimp array. As there are multiple users, alexey's suggestion doesn't work out anymore.
This stil doesn't work:
#foreach($mailchimp as $key => $user)
{{$user}}
#endforeach
You don't need to iterate over $user. If $mailchimp is an array of users, do this:
{{ $mailchimp['email_adress'] }}
{{ $mailchimp['merge_fields']['FNAME'] }} {{ $mailchimp['merge_fields']['LNAME'] }}
Since you are only interested in printing the values in your array, you can use array_flatten to get rid of the nested arrays, and then loop through the result:
#foreach(array_flatten($mailchimp) as $userData)
{{$userData}}
#endforeach
I'm trying to loop through an array provided from facebook graph api. The initial array holds two fields (data, and paging). The data field is also an array filled with 50+ items.
array:2 [▼
"data" => array:77 [▶]
"paging" => array:2 [▶]
]
and opened:
array:2 [▼
"data" => array:77 [▼
0 => array:5 [▼
"id" => "238123092879087er098234_28365"
"picture" => "https://scontent.xx.fbcdn.net/hphotos-xft1/v/t1.0-0/s130x130/12235138_10we2133658asdasdfafsasf5816390956_3188793651778686071_n.jpg?oh=eb8f907a1e8df5efe99cb2b9fafa9c05&oe=56E5627B"
"message" => """
some new GIN available # TasTToe!!\n
\n
MASCARO 9 GIN 40°\n
Alkkemist GIN \n
ATOMIC GIN 40° FROM AtomicDistillers\n
Elephant Gin\n
PLATU LONDON DRY GIN 39°
"""
"link" => "https://www.facebook.com/2381232313223159570563/photos/a.238553749527504.54095.238123159570563/1036585816390956/?type=3"
"full_picture" => "https://scontent.xx.fbcdn.net/hphotos-xft1/v/t1.0-9/12235138_1032365824332445816390956_318234438793651778686071_n.jpg?oh=21fcf828fac0dd49e125b13028d57bfb&oe=56EB6A10"
]
While using the foreach of the facebook results I try to loop through the data field for all the contents yet I am returned with error:
Trying to get property of non-object (View: /var/www/web/elephantegin/htdocs/resources/views/socialApps/facebook.blade.php)
This is the code I used:
#foreach($results->data as $result)
<p>poops</p>
#endforeach
and alternatively this:
#foreach($results as $result)
#foreach($result->data as $data)
<p>help</p>
#endforeach
#endforeach
I've done this times before with no problem. In my controller use json_decode on the results before I push them to the view. How can i call this foreach properly?
If I get you right, then you have an array, but trying to get property. That is how it should be:
#foreach($results['data'] as $result)