I've got a foreach statement that on an item that has both objects and arrays in it.
foreach($result as $data)
that contains both arrays and objects. how do i specify the foreach to only select to loop through one or the other? when it loops through them all it takes forever
I had tried foreach($result->data as $data) but then it errors on the arrays telling me it is trying to get property of an object, which is understandable. once I add an if statement to check if the first result is an object it almost triples the script run time since there are so many results.
Well you could just use is_object() and is_array() (both return a boolean):
if (is_object($var)) {
// do something
} else if (is_array($var)) {
// well then, do something else
}
Related
I am working on a WordPress plugin for a specific theme but have a general question,
I have an array and want to do something with each object and return the result.
everything is Ok but the "foreach" only works for the first object of array and I think its because of "return" but for some reasons I cannot use "echo" instead of return.
this is my code:
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field = get_field($value);
}
return $user_field;
}
I have read other similar topics but passing the variable to another function to do the "return" job for me also not works
Your doubt: the "foreach" only works for the first object of array and I think its because of "return"
No this not for return it's because of variable overwriting inside the foreach() loop every time. Actually you're not returning only the first element, here you're returning the last element because you're overwriting $user_field variable every time within foreach() loop
Try instead to push result to it using $user_field[] and then you're good to go
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field[] = get_field($value);
}
return $user_field;
All the functions work until the return keyword. You need to create a new array and append all the edited elements to it and then return it.
$user_fields = array();
foreach ($cast_list as $value)
{
array_push($user_fields, get_field($value));
}
return $user_fields;
Or you even can work on each field right in the loop and return nothing.
I have a class that does the MySQL stuff for me.
I have 1 to n rows in a MySQL Table and want to query specific results.
To query a table, I can now use
$db->select('tablename', '*');
$res = $db->Result()
to get the results as an associative array.
Now if I want to loop through, I have to check if there is one or more results and then either display that one result or loop through the results.
This bloats up my code and I would like to find a way to combine both results.
At the moment, I am doing this stuff like so:
if(is_array($res[0]){
//we have more than one result
foreach($res as $something)
{
//do stuff here
}
}
else
{
//do the same stuff as above here but now with other variables since $something is only filled in the foreach loop
}
Now as said, I would love to combine those two and have only one piece of code to display the results (or work further with them)
Change the input data structure into the format the loop expects, then iterate through it in the loop:
if(!is_array($res[0]){
$res[0] = [$res[0]];
}
foreach($res as $something)
{
//do stuff here
}
I would suggest you to switch to some wide deveoped classes like PDO (http://php.net/manual/en/book.pdo.php) or simply add a check in your Result method that returns an empty array in cases there are no results
function Result() {
// stuff to fetch and fill $arr;
return (is_array($arr[0])) $arr : array();
}
I have a need to check if the elements in an array are objects or something else. So far I did it like this:
if((is_object($myArray[0]))) { ... }
However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).
The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.
foreach($myArray as $element) {
$areObjects = (is_object($element));
break;
}
if(($areObjects)) { ... }
But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.
you can use reset() function to get first index data from array
if(is_object(reset($myArray))){
//do here
}
You could get an array of keys and get the first one:
$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
try this
reset($myArray);
$firstElement = current($myArray);
current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.reset.php
I am trying to run the following code in PHP to query a MongoDB:
<?
$m = new Mongo(); // connect
$dogs = $m->dogs;
$races = $dogs->newdogs;
$js = "function() {
return this.location == 'SHEFFIELD'
}";
$dataSet = $races->find(array('$where' => $js));
foreach ($dataSet as $r){
}
?>
When I run this and watch the console, I see the query being run once.
When I change the foreach loop to be nested within another one like this:
foreach(range(1,5) as $test){
foreach ($dataSet as $r){
}
}
I see the query being run 7 times in the console?
Is this something stupid I am doing? A scoping issue? Or am I just misunderstanding how MongoDB is supposed to work?
Thanks
AH
This happens because $dataSet is a MongoCursor, not an array. A MongoCursor is a representation of a query. It will be turned into an array "on-demand", that means that when you use foreach on it, $dataSet is converted into an array by simply querying.
Since you do it within another loop, the MongoCursor is executed every time it encounters the foreach. If you don't want that behaviour, you can use iterator_to_array, since a MongoCursor is just an iterator:
$executed = iterator_to_array($dataSet); // Actual query execution
foreach($executed as $r) { // Iterate the array, not the iterator
// Hic sunt ponies
}
EDIT: Keep in mind that iterator_to_array converts the entire result set into an array in memory. If you have a very big result set, this can cause huge and unnecessary memory consumption. It's advisable to stick with a single foreach call, since it will only load one single row into memory at once.
I've been looking into this problem for a couple of days now and I just can't seem to figure it out.
I'm trying to do something simple, I thought, just looping through an array.
This is a screenshot of the array: http://cl.ly/image/3j2J3x1C3B0j
I'm trying to loop through all the 'Skills' array, there the "Skill' array and inside that grabbing the "Icon".
For this I made 2 loops:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills as $skill)
{
//print_r($skill['skill']);
}
}
Unfortunaly this doesn't work, in laravel. I'm getting the "Undefined index: skill" error. It does work when I tried it outside , as a standalone script.
Out side both of the loops I can select the icon with:
print_r($hero_data['skills']['active'][0]['skill']['icon']);
I'm sure I'm overlooking something stupid...
Thanks a lot for the help,
Looking at what you've said from the other solutions posted here, it's clear that you are looping through the sub arrays and not all of those sub arrays contain the keys that your further loops are looking for.
Try this:
foreach ($hero_data['skills']['active'] as $skills) {
if (isset($skills['skill']['icon'])) {
print_r($skills['skill']['icon']);
}
}
Because, for example, if $hero_data['skills']['active'][8] doesn't actually have a skill array or a ['skill']['icon'] array further down, then the loop will throw the errors you have been reporting.
The nested array keys you are looking for must be found in every iteration of the loop without fail, or you have to insert a clause to skip those array elements if they aren't found. And it seems like your $hero_data array has parts where there is no ['skill'] or ['icon'], so therefore try inserting one or more isset() checks in the loops. Otherwise, you need to find a way of guaranteeing the integrity of your $hero_data array.
Your game looks interesting by the way!
Inside skills you have an 'active' attribute and it contains the array you need, so you need to change your code to this:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills['active'] as $skill)
{
//print_r($skill['skill']);
}
}
Try:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills as $skillState)
{
foreach ($skillState as $skill)
{
print_r($skill['skill']);
}
}
}
You simply need to iterate the active index of the array. this should work :
foreach ($hero_data['skills']['active'] as $skills) {
print_r($skills['skill']['icon']);
}