PHP - 更改JSON文件中的值

时间:2015-11-08 05:22:37

标签: php json

我有以下php代码从另一个页面接收一些变量(通过POST发送)。

根据Ad_id和姓名...我正在尝试在“有效”或“无效”之间切换状态。

然而,当我执行此操作时(使用正确的POST数据)...它似乎没有更新任何内容。我做错了什么?

e.g。当我通过有效广告发送时,请输入姓名& status ...然后去查看JSON文件,它没有将'active'切换为'inactive'。

PHP:

<?php

// Get the post variables
$ad_id = $_GET['ad']; 
$name = $_GET['name']; 
$status = $_GET['status']; 

// Get the JSON file
$json = file_get_contents('test.json');

// Decode Json into an array
$json = json_decode($json,true);

// Within the array.. find the ad that matches the POST variable.
foreach ($json['ads'] as $ad) {
    if ($ad['id'] == $ad_id) {

        // Within that Ad... find the candidate that matches the POST variable.
        foreach ($ad['candidates'] as $candidate) {
            if ($candidate['name'] == $name) {

                // Within that candidate... check the value of 'status'.
                if ($candidate['status'] == 'active') {

                    // If active, update the status to 'inactive'.
                    $candidate['status'] = 'inactive';

                } else {

                    // If inactive, update the status to 'active'.
                    $candidate['status'] = 'active';

                }

            }

        }

    }

}

// Encode the array as JSON again
$json = json_encode($json);

// Save the JSON back to the server
file_put_contents('test.json', $json, LOCK_EX);

?>

JSON:

{
    "ads": [
        {
            "id": "12345678",
            "hirername": "Demo Bar",
            "candidates": [
                {
                    "status": "active",
                    "name": "Gregory Jones",
                    "dist": "Richmond (4km away)",
                    "exp1": "Barman at City Bar for 2 years",
                    "avail1": "Mon to Fri - Morning, Evening & Night",
                    "visa": "Australian Citizen",
                    "call": "0413451222"
                },
                {
                    "status": "active",
                    "name": "Jackie Linton",
                    "dist": "Box Hill (13km away)",
                    "exp1": "Bar girl at Collins Bar for 1 year",
                    "avail1": "Mon to Fri - Morning & Evening",
                    "visa": "Working holiday visa",
                    "call": "0413456555"
                }
            ]
        }
    ]
}

3 个答案:

答案 0 :(得分:1)

您应该使用foreach($items as &$item)语法链接来迭代数据 然后所有更改都将在原始结构中。

现在,您可以创建副本,同时进行迭代,修改副本,并且不做任何更改。

// Get the post variables
$ad_id = $_GET['ad']; 
$name = $_GET['name']; 
$status = $_GET['status']; 

// Get the JSON file
$json = file_get_contents('test.json');

// Decode Json into an array
$json = json_decode($json,true);

// Within the array.. find the ad that matches the POST variable.
foreach ($json['ads'] as &$ad) {
    if ($ad['id'] == $ad_id) {

        // Within that Ad... find the candidate that matches the POST variable.
        foreach ($ad['candidates'] as &$candidate) {
            if ($candidate['name'] == $name) {

                // Within that candidate... check the value of 'status'.
                if ($candidate['status'] == 'active') {

                    // If active, update the status to 'inactive'.
                    $candidate['status'] = 'inactive';

                } else {

                    // If inactive, update the status to 'active'.
                    $candidate['status'] = 'active';
                    }

            }

        }

    }

}

// Encode the array as JSON again
$json = json_encode($json);

// Save the JSON back to the server
file_put_contents('test.json', $json, LOCK_EX);

答案 1 :(得分:0)

您的代码中有错误。您为阅读和比较值所做的工作是正确的。

但在写作时,您尚未使用 import javax.swing.JOptionPane; public class MusicPlaylist { // the maximum number of songs the music playlist can hold public static final int MAX_SONGS = 3; public static void main(String[] args) { // create arrays and size counter int size = 0; String[] songsTitles = new String[MAX_SONGS]; double[] songsLength = new double[MAX_SONGS]; // Enter Songs while (true) { // check max number of songs if (size >= MAX_SONGS) { JOptionPane.showMessageDialog(null, "Max number of songs reached."); break; } // Get title or exit command String title = JOptionPane .showInputDialog("Insert song #" + (size + 1) + " title (or Cancel to finish adding songs):"); if (title == null) break; // check if there is a title if (title.isEmpty()) { JOptionPane.showMessageDialog(null, "Title must not be null.", "Error", JOptionPane.ERROR_MESSAGE); continue; // start from the top break; } // Get length double length; try { length = Double .parseDouble(JOptionPane.showInputDialog("Insert song" + (size + 1) + " length is minutes: ")); if (length <= 0) throw new NumberFormatException(); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Length must not be a valid, posite double number.", "Error", JOptionPane.ERROR_MESSAGE); continue; // start from the top } // Add song songsTitles[size] = title; songsLength[size++] = length; } // show list and allow to remove songs while (size > 0) { // if size <=0, nothing to remove // show list String list = ""; for (int i = 0; i < size; i++) { list += songsTitles[i] + " '+ songsLength[i] + 'min/n"; } JOptionPane.showMessageDialog(null, list); // get title or exit command String title = JOptionPane.showInputDialog("Insert title to delete(or Cancel to finish removing songs):"); if (title == null) break; // Find and delete song or show error message boolean found = false; for (int i = 0; i < size; i++) { if (songsTitles[i].equals(title)) // Delete song by shifting following songs over it in the // array for (int j = i + 1; j < size; j++) { songsTitles[j - 1] = songsTitles[j]; songsLength[j - 1] = songsLength[j]; } size--; found = true; } } **if (!found) {** JOptionPane.showMessageDialog(null, "Song not found", "Error", JOptionPane.ERROR_MESSAGE); } // Show report String list = "*** REPORT ***/n"; double total = 0; for (int i = 0; i < size; i++) { list += songsTitles[i] + " " + songsLength[i] + "mins/n"; total += songsLength[i]; } list += "/nTotal length: " + total + " minutes."; JOptionPane.showMessageDialog(null, list); } } 变量的状态。

你正在写作。

$json

上面你使用变量if ($candidate['status'] == 'active') { $candidate['status'] = 'inactive'; } else { $candidate['status'] = 'active'; }

写入文件时,

$candidate

修改

$json = json_encode($json);  <------- $json is used. Where is $candidate??
$ret = file_put_contents('test.json', $json, LOCK_EX);

答案 2 :(得分:0)

/**
 * Problem:
 *
 * - We have 2 variables
 *   $adId: The id of the ad
 *   $name: The name of the candidate
 *
 * - We want to update the status of the candidate depending the current status
 */

// Fake JSON datas
$json = '{

  "ads": [
    {
      "id": "238",
      "hirername": "Demo Bar",
      "candidates": [
        {
          "status": "active",
          "name": "Gregory Jones"
        },
        {
          "status": "active",
          "name": "Jackie Linton"
        }
      ]
    },
    {
      "id": "239",
      "hirername": "Apple",
      "candidates": [
        {
          "status": "inactive",
          "name": "Steve jobs"
        }
      ]
    }
  ]

  }';

// Input variables
$adId = 238;
$name = 'Jackie Linton';

// Convert json as an array (we use true as a second param for that)
$data = json_decode($json, true);

// We fetch only the ads entity from the array
$ads = $data['ads'];

// Loop the ads
foreach ($ads as $adIndex => $ad)
{

  // Check if it's the right ad
  if ($ad['id'] == $adId)
  {
    // Loop candidates
    foreach ($ad['candidates'] as $candidateIndex => $candidate)
    {

      // Sanitize strings for a good check
      $name = trim(strtolower($name));
      $candidateName = trim(strtolower($candidate['name']));

      // We found the right candidate
      if ($name == $candidateName)
      {


        // Change status
        if ($candidate['status'] == 'inactive')
        {
          $data['ads'][$adIndex]['candidates'][$candidateIndex]['status'] = 'active';
        }
        else
        {
          $data['ads'][$adIndex]['candidates'][$candidateIndex]['status'] = 'inactive';
        }

      }

    }

  }

}

// We changed the status.
echo '<pre>';
var_dump($data);
echo '</pre>';

使用该代码(经过测试和工作),您将了解您的问题: - 您将数据保存在“本地”变量而不是全局JSON中。