json php 数组读写_PHP如何将数据写入JSON?

I am newer for php. I want make php page cache, query data from mysql and store data into json format.

I have many questions:

which type of file should I store? .json or .txt or .cache? for I also need use json decode return datas into page.

I want use cron tab, make many mysql queries and write into one json file. what write code should I choose? fopen, fwrite or file_get_contents or other command? (do not cover the data, but continue write. I will deleted the file and renewer it at the next cron time)

If a multi write into a json data (10 or more mysql query at the same time and write into a same json file, each json child format like {name: ".$row['name']."}), how to completed a top { and bottom } to make a standad json data format?

{ //how to add this one

{name: ".$row['name']."}

{name: ".$row['name']."}

// many name from 10 more mysql queries

} //and this one

Thanks.

解决方案which type of file should I store

It doesn't matter. There is no fixed extension, but I would pick .json just to make it clear what the file is supposed to contain.

what write code should I choose?

Just use file_put_contents to put the JSON string (see next section) into a file.

each json child format like

You really do not want to use that method. It might work for a while, but becomes very complex when you need to handle things like quoting and special-character escapes. Instead of re-inventing the wheel, use PHP's built-in JSON functions for this.

Create the data-structure you want using PHP's strings, numbers, and arrays, and then rely on json_encode to turn it into a string.

The main thing to be careful of is that depending on how your php array() looks, you might get JSON [] versus {}.

Newtonsoft.Json是一个功能强大的JSON框架,它提供了读取和写入JSON数据的方法。在处理JSON数组时,我们可以使用Newtonsoft.Json提供的一些方法来实现。 首先,我们需要将JSON数组转换为字符串格式,然后使用Newtonsoft.Json库中的JArray对象进行读写操作。下面是一个读取JSON数组的示例代码: ```csharp string json = "[1, 2, 3, 4, 5]"; // JSON数组字符串 JArray jsonArray = JArray.Parse(json); // 将字符串转换为JArray对象 foreach (var item in jsonArray) { Console.WriteLine(item); // 输出数组中的每个元素 } ``` 在上面的代码中,我们首先将JSON数组的字符串表示形式转换为JArray对象。然后,我们可以使用foreach循环遍历JArray对象中的每个元素,并进行相应的操作。 如果我们想写入一个JSON数组,我们可以创建一个JArray对象,并向其中添加元素。下面是一个写入JSON数组的示例代码: ```csharp JArray jsonArray = new JArray(); // 创建一个JArray对象 for (int i = 1; i <= 5; i++) { jsonArray.Add(i); // 向JArray对象添加元素 } string json = jsonArray.ToString(); // 将JArray对象转换为字符串格式 Console.WriteLine(json); // 输出JSON数组的字符串表示形式 ``` 在上面的代码中,我们首先创建一个空的JArray对象,然后使用for循环向JArray对象中添加元素。最后,我们将JArray对象转换为字符串表示形式,并进行相应的操作。 通过使用Newtonsoft.Json库的JArray对象,我们可以方便地读取和写入JSON数组数据。更多关于Newtonsoft.Json的使用方法,请参考官方文档或其他相关资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值