回显特定的数组项,并在if else语句中使用它们

时间:2016-06-07 14:40:38

标签: php arrays json if-statement

我正忙着根据数组中的项目创建一个on和off开关。 我不打算从已经发生的JSON中提取数据。

该数组是从API创建的,并以JSON格式返回。

$json = file_get_contents($url);

$data = json_decode($json,true);

print_r($data);

print_r结果如下:

Array ( 
    [GetDeviceListResult] => Array ( 
        [Devices] => Array ( 
            [0] => CanvasControllerDeviceCanvas Controller 1 
            [1] => LaCie 324 (2- Intel(R) Display 
            [2] => Realtek Digital Output (2- Real 
            [3] => SchedulerDevice 
            [4] => SneakerNetDevice 
            [5] => SystemDevice 
        )
        [ServiceStatus] => Success 
    ) 
)

Signs4u

让我们说,我想要ServiceStatus。如果成功,请按绿色按钮,如果失败,请将其设为红色按钮。

我如何做到这一点?

2 个答案:

答案 0 :(得分:1)

我编辑了您的问题并对数组进行了格式化,以便您可以清楚地看到结构。一旦理解了结构,就会很清楚如何导航它!

所以回答你的问题:

$serviceStatus = $data['GetDeviceListResult']['ServiceStatus'];

然后当然:

if($serviceStatus == "Success") {
    // Display a green button!
} else {
    //
}

答案 1 :(得分:0)

更通用的解决方案是创建一个递归函数,在多维数组中搜索给定的键,例如,如果此函数搜索键" ServiceStatus",它将返回&#34 ;成功",或者,如果它搜索密钥" 4",它返回" SneakerNetDevice",这是功能:

<?php
// FUNCTION THAT SEARCHES A KEY IN A MULTIDIMENSIONAL ARRAY.
// RETURNS VALUE FOUND, OR EMPTY STRING IF NOT FOUND.
function search_key ( $arr,$search_key )
{ $value = ""; // EMPTY IF NOTHING IS FOUND.
  $keys = array_keys( $arr ); // GET ALL KEYS FROM CURRENT ARRAY.
  foreach ( $keys as $key ) // LOOP THROUGH ALL KEYS IN ARRAY.
    if ( is_array( $arr[ $key ] ) ) // IF CURRENT ITEM IS SUB-ARRAY...
       if ( array_key_exists( $search_key,$arr[ $key ] ) ) // IF ARRAY CONTAINS KEY
         { $value = $arr[ $key ][ $search_key ]; // VALUE FOUND.
           break;
         }
    else $value = search_key( $arr[ $key ],$search_key ); // ENTER SUB-ARRAY.
  return $value;
}

// EXAMPLE ARRAY.
$arr = Array ( 
            "GetDeviceListResult" => Array ( 
                "Devices" => Array ( 
                    "0" => "CanvasControllerDeviceCanvas Controller 1",
                    "1" => "LaCie 324 (2- Intel(R) Display",
                    "2" => "Realtek Digital Output (2- Real", 
                    "3" => "SchedulerDevice",
                    "4" => "SneakerNetDevice",
                    "5" => "SystemDevice"
                ),
                "ServiceStatus" => "Success"
            ) 
        );

// HOW TO USE FUNCTION.
if ( search_key( $arr,"ServiceStatus" ) == "Success" )
     echo "<button>Green button</button>";
else echo "<button>Red button</button>";
echo "<br/>";
if ( search_key( $arr,"4" ) == "SneakerNetDevice" )
     echo "<button>Blue button</button>";
else echo "<button>Yellow button</button>";
?>