如何使用foreach循环遍历此数组?

时间:2017-01-23 06:47:47

标签: php

我想用foreach循环遍历我的数组但是我的结果好坏参与。

下面的数组存储在变量$result中。

当我运行foreach ($result as $call) {时,尽管数组中有3个项目,但它只循环一次。有人可以解释原因吗?

谢谢。

Array
(
    [item] => Array
        (
            [0] => Array
                (
                    [CallRef] => 1025742698
                )
            [1] => Array
                (
                    [CallRef] => 1025786953
                )
            [2] => Array
                (
                    [CallRef] => 1025786953
                )
        )
)

4 个答案:

答案 0 :(得分:3)

这是多维的,所以你的第一个数组只有一个索引;因此,1个结果,恰好是另一个数组。

你想要做这样的事情。

foreach($result['item'] as $res){
    //some action
}

此处有更多信息:Looping a multidimensional array in php

答案 1 :(得分:2)

#include <stdio.h>
#include <conio.h>
#include <termios.h>
#include <unistd.h>

void main()
{
   int fd,a,n;
   fd =open("/dev/ttyUSB0",O_RDWR | ONOCTTY);
   if(fd==-1)
   {
         printf("\n error in opening the port \n");
   }
   else
         printf("port successfully opened");
    struct termios SerialPortSettings;
    tcgetattr(fd,&SerialPortSettings); 
    cfsetispeed(&SerialPortSettings,B115200); |
    cfsetospeed(&SerialPortSettings,B115200); 
    SerialPortSettings.c_cflag &= PARENB;
    SerialPortSettings.c_cflag &= ~CSTOPB;
    SerialPortSettings.c_cflag &= ~CSIZE;
    SerialPortSettings.c_cflag |= CS8;
    SerialPortSettings.c_cflag &= CRTCTS;
    SerialPortSettings.c_cflag |= (CREAD | CLOCAL);
    SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);
    SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    tcsetattr(fd,TCSANOW,&SerialPortSettings);
    char write_buffer[] = "A"; 
    int  bytes_written  =  0 ;   

    bytes_written = write(fd,write_buffer,sizeof(write_buffer));
    tcgetattr(fd, &SerialPortSettings);                           

    //Configure Baudrate()
   //Configure data bits()                                         

    SerialPortSettings.c_cflag |= CREAD | CLOCAL;//enable receiver

    /* Setting Time outs */                                       
    SerialPortSettings.c_cc[VMIN]  = 10; /* Read 10 characters */  
    SerialPortSettings.c_cc[VTIME] = 0;  /* Wait indefinitely   */
    tcsetattr(fd,TCSANOW,&SerialPortSettings);
    char read_buffer[32];                
    int  i=0,bytes_read = 0;                 

    bytes_read = read(fd,&read_buffer,32);
    for (i=0;i<bytes_read;i++)
    {
           printf("Char read : %x\n",read_buffer[i]);
    }

答案 2 :(得分:1)

试试这样..

   foreach ($result['item'] as $key => $value)
      {
       echo $value['CallRef']."<br/>"
      }

答案 3 :(得分:0)

一起去吧。如果你的主阵列如下:

$data=array('item' => array(array('CallRef' => 1025742698),array('CallRef' => 1025786953), array('CallRef' => 1025786953)));

foreach($data['item'] as $data_res)
{
    echo $data_res['CallRef']."</br>";
}