2017-05-09 33 views
0

我有這樣的格式的數組:如何搜索扔了multidemsional陣列找到PHP中的specfic值

array(2) { 
    [0]=> 
    array(8) { 
    ["id"]=> 
    string(2) "12" 
    ["recipient_id"]=> 
    string(2) "18" 
    ["sender_id"]=> 
    string(2) "13" 
    ["unread"]=> 
    string(1) "1" 
    ["notifications_type"]=> 
    string(16) "booking.accepted" 
    ["notifications_parameters"]=> 
    string(24) "Booking request accepted" 
    ["reference_id"]=> 
    string(2) "12" 
    ["created_at"]=> 
    string(19) "2017-05-09 20:34:42" 
    } 
    [1]=> 
    array(8) { 
    ["id"]=> 
    string(2) "13" 
    ["recipient_id"]=> 
    string(2) "18" 
    ["sender_id"]=> 
    string(2) "13" 
    ["unread"]=> 
    string(1) "1" 
    ["notifications_type"]=> 
    string(23) "booking.paymentrequired" 
    ["notifications_parameters"]=> 
    string(28) "Payment required for booking" 
    ["reference_id"]=> 
    string(2) "12" 
    ["created_at"]=> 
    string(19) "2017-05-09 20:34:42" 
    } 
} 

我想在我的代碼做一個動作時,$ nofications_type的價值匹配任何這三個選項:

// booking.requested 
// booking.accepted 
// booking.rejected 

booking.accepted和booking.rejected都爲$ USER_ID

booking.requested是爲$ coach_id

陣列可以具有對於每個請求,這在本多維數組

  //remove the notification for the booking request as the user has now viewed it 
      if ($user_id == 1) { 

       //messy code - just in case this booking is accepted 
       $notifications_type = "booking.accepted"; 
       ModelNotifications::newInstance()->updateUserNotification($userId, $notifications_type, $id); 
       //messy code - just in case this booking is accepted  

       $notifications_type = "booking.rejected"; 

      } elseif ($coach_id == 1) { 

       $notifications_type = "booking.requested"; 

      } 

     ModelNotifications::newInstance()->updateUserNotification($userId, $notifications_type, $id); 

     // more code 

在上REFERENCE_ID值中引用在每個陣列做一個的if-else並調用我的第一,如果內部模型3個可能的條目部分檢查值是否爲booking.accepted看起來不太好,最好的方法是什麼?

+0

你想讀取數組或創建它?我問,因爲它似乎是在下面的代碼中設置類型:'$ notifications_type =「booking.accepted」;' – Scriptable

+0

我已經有數組了,所以它會讀它 – xop32

+0

$ nofications_type從數組值設置,然後我在ModelNotifications中用這個值做一個動作 – xop32

回答

0

switch語句是完美的檢查,對多種可能的情況下

東西
switch ($booking["notification_type"]) { 
    case "booking.accepted": 
     // do what you need for accepted 
     break 
    case "booking.requested": 
     // do what you need for requested 
     break 
    case "booking.rejected": 
     // do what you need for rejected 
     break 
} 

你也可以與其他案件結合起來,例如,其中$notification_type == "booking.accepted" && $user_id == 12但隨後交換機將switch (true) { ...