(PHP)使用foreach循环访问数组中的特定项

时间:2015-08-19 03:45:10

标签: php arrays foreach

以下是$result数组的内容:

Array (
   [ts] => (somenumber)
   [_id] => (theid)
   [state] => sent
   [subject] => Test message
   [email] => (some email)
   [tags] => Array ( )
   [opens] => 0
   [clicks] => 0
   [smtp_events] => Array ( )
   [resends] => Array ( )
   [sender] => (some email)
   [template] => (some template)
   [opens_detail] => Array ( )
   [clicks_detail] => Array ( )
) 

我想访问[state] => sent,以便我可以打印状态,即是否已发送电子邮件。下面是我的代码,我尝试使用foreach循环检索它:

$result = $GLOBALS['mandrill']->messages->info($id);

// Get the status of the email
foreach ($result as $key => $message) {
    $status = $message['state'];
}

我收到错误Notice: Undefined index: state

我做错了什么?

3 个答案:

答案 0 :(得分:1)

简化:

import UIKit
import Parse

class HomePageViewController: UIViewController, UITableViewDelegate   {

@IBOutlet weak var homPageTableView: UITableView!
var imageFiles = [PFFile]()
var imageText = [String]()



override func   viewDidLoad() {
    super.viewDidLoad()

    // DO any additional setup after loading the view
    var query = PFQuery(className: "Posts")
    query.orderByAscending("createdAt")
    query.findObjectsInBackgroundWithBlock {
        (posts : [AnyObject]?, error : NSError?) -> Void in

        if error == nil {
            //success fetxhing objects
            println(posts?.count)
            for post in posts! {

                self.imageFiles.append(post["imageFile"] as! PFFile) ---------error here
                 self.imageText.append(post["imageText"] as! String)
            }

            println(self.imageFiles.count)


        }else{             println(error)
    }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

答案 1 :(得分:1)

使用replicate循环时,请始终记住foreach是方括号和$key之间的内容是值。试试这个:

$message

$result = $GLOBALS['mandrill']->messages->info($id); // Get the status of the email foreach ($result as $key => $message) { if($key == "status") $status = $message; } 循环不应该以这种方式使用。您只需使用foreach即可。

答案 2 :(得分:0)

如果您只想访问州,请执行以下操作:

$result['state']; //This code finds the first array and the index of state

echo $result;