foreach loop problem - php

Foreach don't work properly because in the a array there are multiple arrays and also objects.
For example:
Array
(
[0] => modelItem Object
(
[name] => Name 1
[option] => Array
(
[0] => modelOption Object
(
[id] => 28383
[price] => 1.70
)
)
[quantity] => 2
)
[1] => modelItem Object
(
[name] => Name 2
[option] => Array
(
[0] => modelOption Object
(
[id] => 28398
[price] => 3.50
)
)
[quantity] => 2
)
[subtotal] => 10.40
[deliveryArea] => modelDeliveryArea Object
(
[postcode] => BL2
)
[delivery] => 1
)
I want foreach only loop on modelItem Object and modelItem Object only, how can that be done?
I have tried doing this:
<?php
foreach ($items as $key => $item) {
echo $item->name;
foreach ($item->option as $o) {
echo $o->price;
}
}
?>
It work fine but I also get an error:
Warning: Invalid argument supplied for foreach()
This is because of subtotal, deliveryArea I think.
Edit: Sorry, fixed the loop code - forgot to add { }

Try:
<?php
foreach ($items as $key => $item) {
if ($item instanceof modelItem) {
echo $item->name;
if (isset($item->option) && is_array($item->option)) {
foreach ($item->option as $o) {
echo $o->price;
}
}
}
}

Okay, the reason your code doesn't work, is because you are mixing types of your arrays. Which means you're going to have problems if you always expect $item to be a class. IF you can, I recommend restructuring your array so that your modelItem objects are in an array by themselves to make life easier.
If you cant... Try this:
<?php
if (is_array($items)) {
foreach ($items as $key => $item) {
if(is_a($item, 'modelItem')) {
echo $item->name;
foreach ($item->option as $o) {
echo $o->price;
}
}
}
}
As a side note is_a() is deprecated in php 5.0 - 5.2 and is now undeprecated in php 5.3. If you are using php 5.0 - 5.2 see yoshi's example.

In array like this I would recommend to check like this:
if(isset($someVar))
{
}
or in your case check if is_array like this:
if(is_array($something))
{
}
You can not loop trough a string in your case subtotal, deliveryArea
I hope it helps!

Related

How to fetch non-empty Array from an Array

The Array contains some non-empty arrays . i need to fetch respective non-empty array and print the data . eg: array 2 has variable as importTroubles->troubleMessage how can i print that?
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
[2] => stdClass Object
(
[return] => stdClass Object
(
[failureMessage] =>
[importTroubles] => stdClass Object
(
[kind] => ParseError
[rowNumber] => 1
[troubleMessage] => Field "number1" has invalid value: "+16046799329". Invalid phone number //need to print this..
)
[keyFields] => number1
[uploadDuplicatesCount] => 0
[uploadErrorsCount] => 1
[warningsCount] => stdClass Object
(
)
[callNowQueued] => 0
[crmRecordsInserted] => 0
[crmRecordsUpdated] => 2
[listName] => new camp from CRM1-TargetList-CRM
[listRecordsDeleted] => 0
[listRecordsInserted] => 2
)
)
[3] => stdClass Object
(
)
[4] => stdClass Object
(
)
)
im trying with this method :
foreach($result as $object) {
foreach ($object as $items) {
if($items !== '')
{
foreach ($items as $item) {
echo "ERROR".$item->troubleMessage;
}
}
}
}
Thanks for your efforts
Make use of php function empty()
Change your if condition as in below code :
foreach($result as $object) {
foreach ($object as $items) {
if( !empty($items) )
{
foreach ($items as $item) {
if( isset($item->troubleMessage) )
{
echo "ERROR".$item->troubleMessage;
}
}
}
}
}
Now it will echo only if $items has values.
You don't have to iterate each object if you're only looking for a single specific item nested within it. You can just refer to that item directly.
foreach ($your_array as $object) {
if (isset($object->return->importTroubles->troubleMessage)) {
echo $object->return->importTroubles->troubleMessage;
}
}
If you check if that specific nested object variable is set, it will ignore any empty objects.
change your if($items !== '') to if(!empty($items)) or if($items) or if($items[0]) hope it helps
You could use Collection
use Illuminate\Support\Collection;
$collection = new Collection($result);
$items = $collection->filter(function($object) {
return isset($object->return->importTroubles->troubleMessage);
})->map(function($object) {
return $object->return->importTroubles->troubleMessage;
});

How can i return all the results from my array?

Array
(
[edit] => true
[id] => 1
[type] => Array
(
[0] => LC
)
[userid] => 1
[norooms] => 1
[park] => Central
[start] => 09:00
[end] => 11:00
[length] => 2
[student] => 79
[status] => Rejected
)
<?php
$posted_data = array();
if (!empty($_POST['edit'])) {
$posted_data = json_decode($_POST['editVal'], true);
}
print_r ($posted_data);
foreach ($posted_data as $key => $value) {
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
?>
The array at the top is the jason_decode returned. However with my foreach function it does not display the first index of the array within the array. ie. ( [0] => LC ).
Where am I going wrong?
You need to build a recursive function, something like:
function print_recursively(array $array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
{
print_recursively($value);
}
else
{
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
}
}
Tune it according to your needs.
If you know there is array hierarchy to one level only
Keep printing the values and if the value is an array using is_array.. Iterate again.
foreach($dataArray as $key =>$value){
if(is_array($value)){
foreach($value as $array2Data){
echo $array2Data; //you can use keys as well
}
}
else
echo $value;
}

Is it possible to have more than one key in a loop?

I don't have a problem, but i'm looking for any other maybe better or faster solution.
I have array with two keys ALL and ART:
$myData = Array (
[ALL] => Array (
[0] => Array (
[ID_COUNTRY] => 23
[DELIVERY_DAYS] => 23
[AMOUNT] => 23
)
[1] => Array (
[ID_COUNTRY] => 30
[DELIVERY_DAYS] => 30
[AMOUNT] => 30
)
)
[ART] => Array (
[0] => Array (
[ID_COUNTRY] => 10
[DELIVERY_DAYS] => 10
[AMOUNT] => 10
)
[1] => Array (
[ID_COUNTRY] => 2
[DELIVERY_DAYS] => 20
[AMOUNT] => 20
)
)
)
And have 2 foreach loops to check the values
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
?>
Is possible to do something like this or is the only solution to use two foreach loops without any additional libraries.
<?php
foreach($myData as $key1=>$key2=>$value) {
echo $key1; // [ALL] or [ART]
echo $key2; // [ALL][$key2] or [ART][$key2];
}
?>
If you want to loop over your multi-dimensional array you need your provided code:
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
No way around it without using something that would in the end do this too. There is no speed to be gained here. And if there is it would be a micro-optimization that you should ignore :)
It's not possible. But you could do it as
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
echo $key1;
echo $key2;
}
}
?>
Perhaps not exactly what you are looking for; I still wanted to notify you of it though. You can recursively loop through a multidimensional array, using a RecursiveArrayIterator in combination with a RecursiveIteratorIterator:
$rii = new RecursiveIteratorIterator( new RecursiveArrayIterator( $myData ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $rii as $key => $value )
{
echo $key;
// you can keep track of the current depth with:
$depth = $rii->getDepth();
}

Search multidimensional array by specific key and print the value php

I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?
Example: key['user_id'] this will print all user_id from array. is it possible? please help me thanks
Array
(
[Post1] => Array
(
[id] => 1
[title] => hi
)
[Post2] => Array
(
[0] => Array
(
[user_id] => 1
)
[1] => Array
(
[user_id] => 2
)
)
[Post3] => Array
(
[0] => Array
(
[user_name] => 1
)
)
)
Here is my PHP code:
foreach($post as $key => $value) {
foreach($value as $print => $key) {
if (is_array($key)){
foreach($key as $print2 => $key2) {
echo "<br>".$key2;
}
}else{
echo "<br>".$key;
}
}
}
You can print_r to achive the same results you want with your triple for each.
I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?
You can easily use recursion for such a problem. You can use something along the lines of:
function printValuesByKey($array, $key) {
if (!is_array($array)) return;
if (isset($array[$key]))
echo $key .': '. $array[$key] .'<br>';
else
foreach ($array as $v)
printValuesByKey($v, $key);
}
In your example:
printValuesByKey($array, 'user_id');
will print:
user_id: 1
user_id: 2

Question related to array

I'm trying to print array. All code working fine.But at last I'm getting `ArrayArray'. Can any one solve this problem. many many thanks
here is my array
Array
(
[Post1] => Array
(
[id] => 1
[title] => hi
)
[Post2] => Array
(
[0] => Array
(
[id] => 1
)
)
[Post3] => Array
(
[0] => Array
(
[id] => 1
)
)
)
Here is my PHP Code
foreach($post as $key => $value) {
foreach($value as $print => $key) {
echo "<br>".$key;
}
}
here is output
ID
Array
Array
Try this:
foreach($post as $key => $value) {
foreach($value as $print => $key) {
if (is_array($key)){
foreach($key as $print2 => $key2) {
echo "<br>".$key2;
}
}else{
echo "<br>".$key;
}
}
}
The to string method of an array is to return "Array".
It sounds like you want to view the array for debugging purposes. var_dump() is your friend :)
you are trying to print an array, resulting in Array.
If you want to print an array use print_r
I think the trouble for you is that you have $key in the outer loop and $key in the inner loop so its really confusing which $key you are talking about for starters.
You just want the stuff printed out to debug?
echo "<pre>" . print_r( $post , true ) . "</pre>\n";

Categories