#foreach not looping array as expected - php

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)

Related

How to use nested loop for different arrays in laravel blade template?

I am trying to display the distance for each of my drivers on my database in my view.
When I do die or dump for $pickupDistanceAndTime2 it returns the arrays below, so I need each of the drivers to have its own distance.
0 => array:2 [▶]
1 => array:2 [▶]
2 => array:2 [▶]
return view('driverspane', [
'drivers' => $driver,
'rideDistancenTime' => $pickupDistanceAndTime2,
]);
In my view, I am looping but not getting the way I want it to appear.
#foreach ($drivers as $item)
#foreach ($rideDistancenTime as $data)
{{ $data[0] }}
#endforeach
#endforeach
But the above code keeps repeating distance and time for each of the driver, but I want each of the driver to have its own distance and time only, please see the result I am getting below attached.
The array for $driver returns
#items: array:3 [▼
0 => App\Driver {#317 ▶}
1 => App\Driver {#300 ▶}
2 => App\Driver {#281 ▶}
]
From what you did above, you are just repeating the same values for the first index of the array. You should not do a nested foreach statement.
Rather you could do it this way(using a for statement, provided that the arrays all have same number of keys:
#for ($i=0; $i<count($drivers); $i++)
{{$rideDistancenTime[$i][1]}}
#endfor
Now it should loop properly.
You can use below code to achieve your goal:
$rideDistancenTime;
#foreach ($drivers as $key => $item)
{{ $rideDistancenTime[$key] }}
#endforeach```

Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given - when trying insert db data via eloquent

I'm trying to insert some records into a dabase using Laravel's Eloquent ORM.
The data is stored in an array which looks like this (there are more than one elements in the array)
The initial array which I'm looping through looks like this
array:1 [▼
"Product" => array:4416 [▼
0 => array:9 [ …9]
1 => array:9 [ …9]
2 => array:9 [ …9]
3 => array:10 [ …10]
---------------------------------------------------------------------
array:9 [▼
"ProductCode" => "EWS1025CAM"
"Vendor" => "ENGENIUS"
"ProductType" => "Security - Surveillance Indoor Camera"
"ProductCategory" => "Other"
"ProductDescription" => "Managed AP-CAM Indoor Dual Band 11ac 2T2R 300+867Mbps 2MP dome 4mm IR20m PoE.af μSDHC (Access point - Camera, Power Adapter (12V/1.5A), T-rail mounting kit, mou ▶"
"Image" => "https://www.it4profit.com/catalogimg/wic/1/EWS1025CAM"
"ProductCard" => "https://content.it4profit.com/itshop/itemcard_cs.jsp?ITEM=171208071213009310&THEME=asbis&LANG=ro"
"AttrList" => array:1 [▶]
"Images" => array:1 [▶]
]
I'm looping through it and inserting values like this
foreach ($phpDataArray['Product'] as $key => $value)
{
$insert = new FurnizorProduse();
$insert->product_id = $value['ProductCode'];
$insert->product_data = json_encode($value);
$insert->date = new \DateTime();
$insert->module_id = 58;
$insert->save();
}
Even though the data is inserted correctly into the db, I get "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given".
The line of code causing this is $insert->product_id = $value['ProductCode'];
as if I replace the $value['ProductCode']; wiht an integer let's say, no more errors.
Any ideas ? Thanks !
In one of your iteration of:
$phpDataArray['Product'], you don't have: $value['ProductCode'], it's my assumption.
Try to do:
if(is_array($value) && isset($value['ProductCode'])) {
$insert = new FurnizorProduse();
...
}

Laravel Loop Through Multidimesional Array

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

Laravel 5 JSON / Blade

I am trying to pass a JSON to my view
With this code:
Route::get('json', function() {
$path = storage_path() . "/json/dish.json";
$json = json_decode(file_get_contents($path), true);
return View::make('pages.json')->withJson($json);
});
With {{dd($json)}}
I receive this:
array:1 [▼
"dish" => array:297 [▼
0 => array:2 [▶]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:5 [▶]
...
When I try to display the content of my $json with:
#foreach($json["dish"] as $key => $item)
{{$item}}
#endforeach
I get this error message:
htmlentities() expects parameter 1 to be string, array given (View: /Users/beyerdynamic/Documents/Developer/dev1/resources/views/pages/json.blade.php)
What am I doing wrong here?
By default Laravel tries to escape any variables before input. If you want to avoid it use {!! $item !!}. However, $item is array and it will not help you to show proper values. You will get 'Array' as output. If you want to display correct data use {{ $item['your_key'] }}.

Laravel 5 displaying an Array of Objects returned from Parse.com

I am trying to pass an array of objects to the view and then use the blade templating engine to loop through them.
The data is being returned from a Parse.com query and is structured like this:
[
{
"Params": [],
"difficulty": "Medium",
"exerciseDescription": "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder.",
"exerciseID": "1024",
"exerciseName": "Bicep Curl Sitting on Gym Ball",
"images": [
2758,
2759,
2760
],
"objectId": "9xjQ4WVo6e",
"tags": [
"Dumbbell",
"Gym Ball",
"Flexion"
],
"words": [
"seated",
"dumbbell",
"arm",
"curl"
]
}
]
I am getting this using this query:
public function about()
{
$programmeId = 'T8iqZhtDqe';
$query = new ParseQuery("PrescribedProgrammes");
try {
$programme = $query->get($programmeId);
// The object was retrieved successfully.
} catch (ParseException $ex) {
echo $ex;
// The object was not retrieved successfully.
// error is a ParseException with an error code and message.
}
$exerciseData = $programme->get("exerciseData");
$programmeTitle = $programme->get("prescribedProgrammeTitle");
// return view('pages.about', compact('exerciseData','programmeTitle'));
return view('pages.about')->with('exerciseData', $exerciseData);
}
And to test this I have been trying:
#foreach($exerciseData as $exercise => $value)
{{ $exercise->exerciseName }}
#endforeach
However I am getting a Array to string conversion error. Coming from a angularJS background I am hoping to pass my array of objects to the view and then loop through them as I see fit.
Would this be considered poor form?
EDIT
Running dd($exerciseData)
array:7 [▼
0 => array:9 [▼
"Params" => []
"difficulty" => "Medium"
"exerciseDescription" => "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder."
"exerciseID" => "1024"
"exerciseName" => "Bicep Curl Sitting on Gym Ball"
"images" => array:6 [▶]
"objectId" => "9xjQ4WVo6e"
"tags" => array:6 [▶]
"words" => array:8 [▶]
]
1 => array:9 [▶]
2 => array:9 [▶]
3 => array:9 [▶]
4 => array:9 [▶]
5 => array:9 [▶]
6 => array:9 [▶]
]
I think you're using the key of the array instead of the value. For example the default PHP foreach looks like the following:
foreach($array as $key => $value) {
// code
}
Edit:
After looking at the dump of $exerciseData it appears that PHP is serializing the JSON into an array, so this changes the answer.
If you return this to the view:
return view('quiz.create', compact('programmeTitle', 'exerciseData'));
Then have the following in your view it should work as I have tested it locally:
<h2>{{$programmeTitle}}</h2>
#foreach ($exerciseData as $key => $exercise)
<p>{{$exercise['exerciseName']}}</p>
#endforeach

Categories