如何使用 PHP 为 JSON 创建数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6739871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:07:36  来源:igfitidea点击:

How to create an array for JSON using PHP?

phpjson

提问by Mimmo

From PHP code I want to create an json array:

从 PHP 代码我想创建一个 json 数组:

[
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"}
]

How can I do this?

我怎样才能做到这一点?

回答by David Titarenco

Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php

简单的柠檬挤压:http://www.php.net/manual/en/function.json-encode.php

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

There's a post by andyrusterholz at g-m-a-i-l dot c-o-mon the aforementioned page that can also handle complex nested arrays (if that's your thing).

andyrusterholz at g-m-a-i-l dot c-o-m前面提到的页面上有一个帖子,它也可以处理复杂的嵌套数组(如果这是你的事)。

回答by Shef

Use PHP's native json_encode, like this:

使用 PHP 的 native json_encode,像这样:

<?php
$arr = array(
    array(
        "region" => "valore",
        "price" => "valore2"
    ),
    array(
        "region" => "valore",
        "price" => "valore2"
    ),
    array(
        "region" => "valore",
        "price" => "valore2"
    )
);

echo json_encode($arr);
?>


Update: To answer your question in the comment. You do it like this:

更新:在评论中回答您的问题。你这样做:

$named_array = array(
    "nome_array" => array(
        array(
            "foo" => "bar"
        ),
        array(
            "foo" => "baz"
        )
    )
);
echo json_encode($named_array);

回答by tdammers

Simple: Just create a (nested) PHP array and call json_encodeon it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:

简单:只需创建一个(嵌套的)PHP 数组并调用json_encode它。数字数组转换为 JSON 列表 ( []),关联数组和 PHP 对象转换为对象 ( {})。例子:

$a = array(
        array('foo' => 'bar'),
        array('foo' => 'baz'));
$json = json_encode($a);

Gives you:

给你:

[{"foo":"bar"},{"foo":"baz"}]

回答by Parveen Verma

Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.

每次在 php 中创建 json 的最佳方法是首先转换 ASSOCIATIVE 数组中的值。

After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assocfunction, which also return one associative array.

之后只需简单地使用json_encode($associativeArray). 我认为这是在 php 中创建 json 的最佳方法,因为每当我们在 php 中从 sql 查询中获取结果时,大部分时间我们都使用fetch_assoc函数获取值,该函数也返回一个关联数组。

$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';

... etc.

... 等等。

After that.

在那之后。

json_encode($associativeArray);

回答by dwaskowski

also for array you can use short annotattion:

同样对于数组,您可以使用简短的注释:

$arr = [
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ],
    [
        "region" => "valore",
        "price" => "valore2"
    ]
];

echo json_encode($arr);

回答by iZeeshan

That's how I am able to do with the help of solution given by @tdammers below. The following line will be placed inside foreach loop.

这就是我在下面@tdammers 提供的解决方案的帮助下能够做到的。以下行将放置在 foreach 循环中。

$array[] = array('power' => trim("Some value"), 'time' => "time here" );

And then encode the array with json encode function

然后使用 json encode 函数对数组进行编码

json_encode(array('newvalue'=> $array), 200)

回答by theModerator713

Just typing this single line would give you a json array ,

只需输入这一行,您就会得到一个 json 数组,

echo json_encode($array);

echo json_encode($array);

Normally you use json_encodeto read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.

通常您用于json_encode从 ios 或 android 应用程序读取数据。所以请确保除了准确的 json 数组外,不要回显任何其他内容。

回答by Matthew

$json_data = '{ "Languages:" : [ "English", "Spanish" ] }';
$lang_data = json_decode($json_data);
var_dump($lang_data);

回答by iamasp

<?php 

    $username=urldecode($_POST['log_user']);

    $user="select * from tbl_registration where member_id= '".$username."' ";
    $rsuser = $obj->select($user);
    if(count($rsuser)>0)
    {
        //   (Status if 2 then its expire)    (1= use) ( 0 = not use)

        $cheknew="select name,ldate,offer_photo  from tbl_offer where status=1 ";
        $rscheknew = $obj->selectjson($cheknew);

        if(count($rscheknew)>0)
        {

             $nik=json_encode($rscheknew);
            echo "{\"status\" : \"200\" ,\"responce\" : \"201\", \"message\" : \"Get Record\",\"feed\":".str_replace("<p>","",$nik). "}";
        }
        else
        {
            $row2="No Record Found";
            $nik1=json_encode($row2);
            echo "{\"status\" : \"202\",  \"responce\" : \"604\",\"message\" : \"No Record Found \",\"feed\":".str_replace("<p>","",$nik1). "}";
        }
    }
    else
    {
        $row2="Invlid User";
        $nik1=json_encode($row2);
        echo "{\"status\" : \"404\", \"responce\" : \"602\",\"message\" : \"Invlid User \",\"feed\":".str_replace("<p>","",$nik1). "}";
    }

 ?>

回答by Jeffrey Meyer

I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.

我创建了一个粗略而简单的 jsonOBJ 类来用于我的代码。PHP 不包含像 JavaScript/Node 那样的 json 函数。您必须以不同的方式迭代,但可能会有所帮助。

<?php

// define a JSON Object class
class jsonOBJ {
    private $_arr;
    private $_arrName;

    function __construct($arrName){
        $this->_arrName = $arrName;
        $this->_arr[$this->_arrName] = array();

    }

    function toArray(){return $this->_arr;}
    function toString(){return json_encode($this->_arr);}

    function push($newObjectElement){
        $this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
    }

    function add($key,$val){
        $this->_arr[$this->_arrName][] = array($key=>$val);
    }
}

// create an instance of the object
$jsonObj = new jsonOBJ("locations");

// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));

$jsonObj->add("location","TestLoc3"); // from key:val pairs

echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>

Will output:

将输出:

Array
(
    [locations] => Array
        (
            [0] => Array
                (
                    [location] => TestLoc1
                )

            [1] => Array
                (
                    [location] => TestLoc2
                )

            [2] => Array
                (
                    [location] => TestLoc3
                )

        )

)


{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}

To iterate, convert to a normal object:

要迭代,转换为普通对象:

$myObj = $jsonObj->toArray();

Then:

然后:

foreach($myObj["locations"] as $locationObj){
    echo $locationObj["location"] ."<br />";
}

Outputs:

输出:

TestLoc1
TestLoc2
TestLoc3

TestLoc1
TestLoc2
TestLoc3

Access direct:

直接访问:

$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];

A practical example:

一个实际例子:

// return a JSON Object (jsonOBJ) from the rows
    function ParseRowsAsJSONObject($arrName, $rowRS){
        $jsonArr = new jsonOBJ($arrName); // name of the json array

        $rows = mysqli_num_rows($rowRS);
        if($rows > 0){
            while($rows > 0){
                $rd = mysqli_fetch_assoc($rowRS);
                $jsonArr->push($rd);
                $rows--;
            }
            mysqli_free_result($rowRS);
        }
        return $jsonArr->toArray();
    }