簡體   English   中英

將json文件轉換為php數組,從數組中選擇隨機名稱

[英]Turn json file into php array to select random name from the array

問題如下:

我將從excel附加到每個名稱的名稱和值(repCode)列表導出到文件中。

然后我想將文件轉換為數組,這樣我就可以有一段代碼從數組中選擇一個隨機名稱並顯示隨機名稱(以及附加到名稱的值(repCode))。

到目前為止,我已經嘗試了很多選項但是我一直在遇到一些我正在努力尋找解決方案的問題。 一個例子是:

<?php

$jsondata = file_get_contents("Names.json");
$json = json_decode($jsondata, true);
$output = '<ul>';
foreach($json['Reps']as $reps){
$output .='<h4>' .$reps['Client']."<h4>";
$output .= "<li>".$reps['Code']."</li>";

}

$output .= "</ul>";
$element = $output[mt_rand(0, count($output) - 1)];

echo $element;

?>

這不起作用。

文件如下:“Names.json”

{
"Reps": [

{"Client":"Jack",
    "repCode":"tt1790861"},
{"Client":"James",
    "repCode":"tt1790862"},
{"Client":"Sam",
    "repCode":"tt1790863"},
{"Client":"Hendry",
    "repCode":"tt1790864"},
{"Client":"Samone",
    "repCode":"tt1790865"},
{"Client":"Judy",
    "repCode":"tt179086"},
{"Client":"Jake",
    "repCode":"tt1790867"},
{"Client":"Amy",
    "repCode":"tt1790868"},
{"Client":"Brandon",
    "repCode":"tt1790869"},
{"Client":"Blake",
    "repCode":"tt17908610"},
{"Client":"Rick",
    "repCode":"tt17908611"},
{"Client":"Morty",
    "repCode":"tt17908612"}       
]
}

然后下面是一些代碼:

<?php
  // JSON string
  $someJSON = "Names.json";

  // Convert JSON string to Array
  $someArray = json_decode($someJSON, true);
  print_r($someArray);        // Dump all data of the Array
  echo $someArray[0]["Client"]; // Access Array data

?>

當我回顯文件時,我沒有得到任何結果。 所以我甚至無法到達我想要使用已轉換為數組的文件的部分,因此我可以使用代碼來選擇隨機名稱+關聯的代碼並顯示它。

任何幫助,將不勝感激。

在您的第一個示例中,您嘗試將$output用作數組,但事實並非如此。 此外,您沒有訪問$element的鍵:

$element = $json['Reps'][mt_rand(0, count($json['Reps']) - 1)];
//or
$element = $json['Reps'][array_rand($json['Reps'])];
echo $element['Client'];
echo $element['repCode'];

對於第二個示例,您實際上並未加載JSON文件,而是忘記了Reps鍵:

$someJSON = file_get_contents("Names.json");
$someArray = json_decode($someJSON, true);
print_r($someArray);
echo $someArray["Reps"][0]["Client"];
//or random
echo $someArray["Reps"][array_rand($someArray["Reps"])]["Client"];
$json = file_get_contents('Names.json');
$reps = json_decode($json, true);
$key = array_rand($reps['Reps']);
$randomRepName = $reps['Reps'][$key]['Client'];
$randomRepCode = $reps['Reps'][$key]['repCode'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM