PHP foreach loop on multi dimensional array - php

having a bit of difficulty with a multi-dimensional array. I have shortened it, but the array looks like this
array(192) {
["count"]=> int(191)
[0]=>array(124) {
[11]=>string(10) "usnchanged"
["homemta"]=>array(2) {
["count"]=>int(1)
[0]=>string(206) "Some String"
}
[12]=>string(7) "homemta"
["proxyaddresses"]=>array(2) {
["count"]=>int(1)
[0]=>string(46) "SMTP:remove=email#email.com"
}
}
}
}
I am trying to get the email addresses which will be listed under proxyaddresses. What I am doing at the moment is the following:
for($i=0; $i<$data["count"]; $i++) {
foreach($data[$i]["proxyaddresses"] as $object) {
print_r($object);
}
}
This gets me the data I need, but inbetween all the data I get a lot of warnings like
Notice: Undefined index: proxyaddresses in index.php on line 88
Warning: Invalid argument supplied for foreach() in index.php on line
88
So I presume it is not liking something. How would I properly do the loop based on the above array structure?
Thanks

It's because proxyaddresses element is not present for each loop. You have to check if it's set or not to avoid warning by using php isset() function.
for($i=0; $i<$data["count"]; $i++) {
if(isset($data[$i]["proxyaddresses"])){
foreach($data[$i]["proxyaddresses"] as $object) {
print_r($object);
}
}
}

for($i=0; $i<$data["count"]; $i++) {
if(!isset($data[$i]["proxyaddresses"])) continue;
foreach($data[$i]["proxyaddresses"] as $object) {
print_r($object);
}
}

Related

PHP - How do I expand all arrays within an array

My code is giving an error when I try to echo all values within an array but also expand and echo the values of any arrays in the original array.
while (list($key, $val) = each($bal)) {
If (is_array($val)){
while (list($k, $v) = each($v)) {
If (is_array($va)){
while (list($ka, $va) = each($va)) {
echo "$ka => $va\n <br>";
}
} else {
echo "$k => $v\n <br>";
}
}
} else {
echo "$key => $val\n <br>";
}
}
The error I am getting is
Warning: Variable passed to each() is not an array or object in
C:\xampp2\htdocs\money\production\simalgorithm1.php on line 234
Line 234 is while (list($k, $v) = each($v)) {
Shouldn't this automatically not be an array as I did a check the line previous? My Syntax must be off I am fairly new to PHP if someone could help me see what I am not seeing I would greatly appreciate it.
Sometimes the simplest solutions are the best one line problem solved.
print_r($bal);
The problem is this line:
while (list($k, $v) = each($v)) {
I think you want this
while (list($k, $v) = each($val)) {
EDIT: I would also point out that your code will not work if the arrays are nested more than a few levels deep. You should consider defining a recursive function or using var_export or var_dump.

For each loop in PHP erroring out "invalid argument supplied"

I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
The error I get is: PHP Warning: Invalid argument supplied for foreach()
For example, empty('') would also be true.
I would recommend to check is_array($scores) && count($scores) instead of empty(), to make sure the api returned useable output (an array) and that this contains elements (count() > 0 which is true).
$scores = TESTAPI::GUL($user->ID);
if (is_array($scores) && count($scores)) {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
} else {
echo "<p>No Scores</p>";
}
Try this -
foreach ((array) $scores as $score) { ...
Looks like $scores is neither an array nor an object...

mysql error msg reading table data (Warning: Invalid argument supplied for foreach() in)

ive this table which is updated and re-ranked every midnight ,
after few days i start getting this msg
Warning: Invalid argument supplied for foreach() in
in last page of pagination to fix it i used to trunk the table and run my code again then its work fine , here is my mysql statement case the issue
mysql_free_result($result);
$i = 0;
$total_amount = count($tweeps);
foreach ($tweeps as $tweep) {
$i++;
if ($total_amount == $i) {
$class = 'divrow divrowlast';
} else {
$class = 'divrow';
}
need to tips to do permanent fix
Without seeing what $tweeps contains its hard to help. You are however missing a closing bracket. For practice you should check if $tweeps is in fact an array though. My assumption is that $tweeps isn't an array.
if (is_array($tweeps)) {
foreach ($tweeps as $tweep) {
$i++;
if ($total_amount == $i) {
$class = 'divrow divrowlast';
} else {
$class = 'divrow';
}
}
}

PHP Array structure

I am trying to generate an MS Excel spread sheet using PHPExcel 1.7.6 . I am having trouble determining the structure of the array expected.
The code that builds up the columns and rows is as follows:
function _headers() {
$i=0;
foreach ($this->data[0] as $field => $value) {
if (!in_array($field,$this->blacklist)) {
$columnName = Inflector::humanize($field);
$this->sheet->setCellValueByColumnAndRow($i++, 4, $columnName);
}
}
$this->sheet->getStyle('A4')->getFont()->setBold(true);
$this->sheet->getStyle('A4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$this->sheet->getStyle('A4')->getFill()->getStartColor()->setRGB('969696');
$this->sheet->duplicateStyle( $this->sheet->getStyle('A4'), 'B4:'.$this->sheet->getHighestColumn().'4');
for ($j=1; $j<$i; $j++) {
$this->sheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($j))->setAutoSize(true);
}
}
function _rows() {
$i=5;
foreach ($this->data as $row) {
$j=0;
foreach ($row as $field => $value) {
if(!in_array($field,$this->blacklist)) {
$this->sheet->setCellValueByColumnAndRow($j++,$i, $value);
}
}
$i++;
}
}
I'm currently getting an 'Invalid argument supplied for foreach()' error.
I would appreciate it if somebody can outline the correct array structure required.
As IsisCode said, it sounds like you're looking in the wrong direction by associating the problem with PHPExcel. That error is generally just saying that the first argument supplied to foreach() isn't an array.
I don't see anything indicating that the problem is explicitly with the initial foreach in the _headers() method though. If there's a non array element in $this->data then your _rows() method could produce the error as well.
Given:
$this->data = Array(
Array('foo' => 'bar'),
'baz'
)
That would cause the second foreach in _rows() to fail, as an example. Your error message should be able to point you to which foreach() is failing, but ultimately it sounds like you've got a non-array element in $this->data where you don't expect it. If that can't be helped, then consider verifying you're dealing with an array before calling foreach:
function _rows() {
$i=5;
foreach ($this->data as $row) {
$j=0;
if(!is_array($row)) { continue; } // Ignore non-array elements
foreach ($row as $field => $value) {
if(!in_array($field,$this->blacklist)) {
$this->sheet->setCellValueByColumnAndRow($j++,$i, $value);
}
}
$i++;
}
Verifying the type of a variable before handing it to a type-specific function is never a bad idea and can save a lot of headache in general.

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Categories