How to Create an Array For Json Using PHP

create JSON array using PHP

Something like this if I understood code correctly :

$varient["0"] = 12121221;
$varient["1"] = 22122111;

$data["varient"] = $varient;
$data["site"] = "google";
$data["click"] = "yes";

$result["data"][]=$data;


$varient["0"] = 33333;
$varient["1"] = 443434;

$data["varient"] = $varient;
$data["site"] = "yahoo";
$data["click"] = "no";

$result["data"][]=$data;

echo json_encode($result);

how to create json array of objects from php array in php?

$a = [41, 64, 51, 42, 65, 52, 66, 67];
sort($a);
$b = [];
foreach ($a as $v) {
$b[] = ['associated_id' => $v];
}
echo json_encode($b);

gives

[{"associated_id":41},{"associated_id":64},{"associated_id":51}, {"associated_id":42},{"associated_id":65},{"associated_id":52},{"associated_id":66},{"associated_id":67}]

Alternatively you can just use the Mark Baker's oneliner in your comments

If you are using an older version of PHP you may have to code it like this

$a = array(41, 64, 51, 42, 65, 52, 66, 67);
sort($a);
$b = array();
foreach ($a as $v) {
$b[] = array('associated_id' => $v);
}
echo json_encode($b);

Creating a json with array inside PHP?

Simply create a numeric-indexed array. Note that you can't have multiple keys with the same name in an array, so you need different names for "Day pass", otherwise you'd be overwriting them:

<?php
$json = [
"json" => [
"Day pass" =>
[40, 10, 99, 50],
"Day pass2" =>
[40, 10, 99, 50],
"Day pass3" =>
[40, 10, 99, 50],
"Day pass4" =>
[40, 10, 99, 50],
],
];
print_r(json_encode($json));

Gives the correct result:

{
"json": {
"Day pass": [40, 10, 99, 50],
"Day pass2": [40, 10, 99, 50],
"Day pass3": [40, 10, 99, 50],
"Day pass4": [40, 10, 99, 50]
}
}

Demo

Using the same key instead, gives you one item:

<?php
$json = [
"json" => [
"Day pass" =>
[40, 10, 99, 50],
"Day pass" =>
[40, 10, 99, 50],
"Day pass" =>
[40, 10, 99, 50],
"Day pass" =>
[40, 10, 99, 50],
],
];
print_r(json_encode($json));

Result:

{
"json": {
"Day pass": [40, 10, 99, 50]
}
}

Demo


The problem with your specific code is that, in order to have json_encode() return a JSON array (instead of an object), the PHP array needs to be a numeric sequential 0-indexed array. What you can do is pass the array through array_values() in order to only preserve the values and reset the keys:

<?php
$open_rates = [];
$open_rates["x"]["0"] = "Sun";
$open_rates["x"]["2"] = "Mon";
var_dump(json_encode($open_rates)); // JSON object
$open_rates["x"] = array_values($open_rates["x"]);
var_dump(json_encode($open_rates)); // JSON array

Demo

How to create json object with php

PHP doesn't use json itself. Just make a regular php array and push it through the json_encode function.

$stuff = array(
array( 'label' => 'name 1', 'value' => 1 ),
array( 'label' => 'name 2', 'value' => 2 ),
array( 'label' => 'name 3', 'value' => 3 ),
);
echo json_encode( $stuff );

How to generate JSON data with PHP?

To generate JSON in PHP, you need only one function, json_encode().

When working with database, you need to get all the rows into array first. Here is a sample code for mysqli

$sql="select * from Posts limit 20"; 
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);

then you can either use this array directly or make it part of another array:

echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);

if you need to save it in a file then just use file_put_contents()

file_put_contents('myfile.json', json_encode($posts));

Creating php json object array inside of array

There's no need to create two separate $question_arr or $answer_arr arrays. Instead, just create one empty result array $resultArr and refactor your code in the following way,

$resultArr = array();
$sql = "SELECT * FROM Questions WHERE product='".$product."'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$resultArr = array('success' => true, 'total' => $result->num_rows);
while($row = $result->fetch_assoc()) {
$resultArr['question'][$row['ID']] = array('id' => $row['ID'], 'product' => $row['product'], 'question' => $row['question']);

//Anwser table results
$sql2 = "SELECT * FROM Answers WHERE question_id='".$row['ID']."'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$resultArr['question'][$row['ID']]['answer'][] = $row2;
}
}
$resultArr['question'] = array_values($resultArr['question']);
} else {
$resultArr = array('success' => false, 'total' => 0);
echo "question 0 results";
}
echo json_encode($resultArr);

How to create a dynamic JSON array in PHP using multiple for eaches?

You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...

// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);

}
echo json_encode($finalArray);


Related Topics



Leave a reply



Submit