converting multidimensional array into json - php

this is my multidimensional array..i know how to encode array to json but not getting actual json expected json result
array (
1 =>
array (
'text' => 'Dashboard',
'spriteCssClass' => 'rootfolder',
'expanded' => 'true',
'id' => '1',
'item_name' => 'Dashboard',
'menu_type' => 'item',
'parent' => '0',
'items' =>
array (
9 =>
array (
'text' => 'Application',
'spriteCssClass' => 'html',
'id' => '9',
'item_name' => 'Application',
'menu_type' => 'header',
'parent' => '1',
'items' =>
array (
),
),
),
),
)
after encoding it into json i am getting the following result
for encodin i used json_encode($array);
{
"1": {
"text": "Dashboard",
"spriteCssClass": "rootfolder",
"expanded": "true",
"id": "1",
"item_name": "Dashboard",
"menu_type": "item",
"parent": "0",
"items": {
"9": {
"text": "Application",
"spriteCssClass": "html",
"id": "9",
"item_name": "Application",
"menu_type": "header",
"parent": "1",
"items": {}
}
}}}
i want the following encoded json
{
"text": "Dashboard",
"spriteCssClass": "rootfolder",
"expanded": "true",
"id": "1",
"item_name": "Dashboard",
"menu_type": "item",
"parent": "0",
"items": [
{
"text": "Application",
"spriteCssClass": "html",
"id": "9",
"item_name": "Application",
"menu_type": "header",
"parent": "1",
"items": {}
}]
}
i tried almost everything but not getting my expected json result
i want remove the array indexing from json like "1" { and also want to add "[" this after every items: column

It looks like you just want to json_encode($yourData[1]) instead of just json_encode($yourData)...

Your array is not 0 indexed, therefore json_encode assumes its an assoc array.
If you 0 index your array, you should get the expected result, or maybe even remove the index assignment completelely:
array (
array (
'text' => 'Dashboard',
'spriteCssClass' => 'rootfolder',
'expanded' => 'true',
'id' => '1',
'item_name' => 'Dashboard',
'menu_type' => 'item',
'parent' => '0',
'items' =>
array (
9 =>
array (
'text' => 'Application',
'spriteCssClass' => 'html',
'id' => '9',
'item_name' => 'Application',
'menu_type' => 'header',
'parent' => '1',
'items' =>
array (
),
),
),
),
)
EDIT***
to remove all numerical indexes / convert all "non-assoc" to normal use:
function normaliseArray($arr,$recurse=True) {
if (!is_array($arr))
return $arr;
if (count(array_filter(array_keys($arr), 'is_numeric')) == count($arr))
$arr = array_values($arr);
if ($recurse) {
foreach($arr as $k => $a) {
$arr[$k] = normaliseArray($a,$recurse);
}
}
return $arr;
}
json_encode(normaliseArray($array));
try that.

json_encode will encode it as is. The best you can do is force the array to start at 0 which would be the same as []:
$array = array_values($array);
$array[0]['items'] = array_values($array[0]['items']);

Related

Transpose a multidimensional array with variable depth (2 levels and 3 levels)

I need to restructure an array containing data in 2 levels and 3 levels. All of the values should be grouped by their indexes, but I need to maintain associative relationships.
Sample input:
$variation = [
"sku" => [
0 => "dSADad",
1 => "ASDAF",
2 => "ASFAS",
],
"Price" => [
0 => "1",
1 => "1",
2 => "1",
],
"Quantity" => [
0 => "123",
1 => "123",
2 => "123434",
],
"attributes" => [
"Color" => [
0 => "5",
1 => "4",
2 => "4",
],
"Size" => [
0 => "3",
1 => "3",
2 => "2",
],
"Material" => [
0 => "7",
1 => "7",
2 => "8",
],
],
];
I want to transform it to be grouped by separate variants. I tried several options but without a successful result. I also tried with JS to add an index to the input before submitting, but it still doesn't work. The only option left is to transform it into PHP.
Desired result:
$variations = [
[
"sku" => "dSADad",
"Price" => "1",
"Quantity" => "123",
"attributes" => [
"Color" => "5",
"Size" => "3",
"Material" => "7",
],
],
[
"sku" => "ASDAF",
"Price" => "1",
"Quantity" => "123",
"attributes" => [
"Color" => "4",
"Size" => "3",
"Material" => "7",
],
],
[
"sku" => "ASFAS",
"Price" => "1",
"Quantity" => "123434",
"attributes" => [
"Color" => "4",
"Size" => "2",
"Material" => "8",
],
],
];
I managed to make this piece of code:
function extractVariation($variations, $key)
{
$variation = [];
foreach ($variations as $property => $values) {
if (isset($values[$key])) {
$variation[$property] = $values[$key];
} else {
$variation[$property] = extractVariation($values, $key);
}
}
return $variation;
}
$newVariations = [];
foreach ($variations['sku'] as $key => $sku) {
$newVariations[] = extractVariation($variations, $key);
}
var_export($newVariations);
See a working example here: https://3v4l.org/l4gJQ
Note that I renamed your $variation array into $variations.
The function is recursive, which allows it to go into the attributes array.
The output is:
array (
0 =>
array (
'sku' => 'dSADad',
'Price' => '1',
'Quantity' => '123',
'attributes' =>
array (
'Color' => '5',
'Size' => '3',
'Material' => '7',
),
),
1 =>
array (
'sku' => 'ASDAF',
'Price' => '1',
'Quantity' => '123',
'attributes' =>
array (
'Color' => '4',
'Size' => '3',
'Material' => '7',
),
),
2 =>
array (
'sku' => 'ASFAS',
'Price' => '1',
'Quantity' => '123434',
'attributes' =>
array (
'Color' => '4',
'Size' => '2',
'Material' => '8',
),
),
)
It is always better to show what you've tried, even if it doesn't work completely. That way people here can see that you're not simply asking them to write code for you, but that you really have a problem.
For your sample data, it is not necessary to use recursion because the input array's depth is known/static.
Traditional array transposition (with a 2d array) is the nesting of two foreach loops and switching the keys between the two levels. With your data, you must conditionally handle the data sets that have 3 levels of depth. Notice the how inside of the is_array() condition, another loop is used to iterate the subarray and push that data into the new appropriate position in the result array.
In all cases, the level containing indexed keys is used as the new first level key and the original first level keys are always used as new second level keys.
Code: (Demo)
$result = [];
foreach ($array as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
if (is_array($v2)) {
foreach ($v2 as $k3 => $v3) {
$result[$k3][$k1][$k2] = $v3;
}
} else {
$result[$k2][$k1] = $v2;
}
}
}
var_export($result);

Push nested element into multidimensional array [duplicate]

This question already has answers here:
How to add elements to an empty array in PHP?
(8 answers)
Push Array inside an Array PHP
(2 answers)
Closed 28 days ago.
I have this array
echo '<script type="application/ld+json">';
$data = array(
'#context' => 'https://schema.org',
'#graph' => array(),
);
$data['#graph'][] = [
"#type" => "ImageObject",
];
$data['#graph'][] = [
"#type" => "BreadcrumbList",
"itemListElement" => array(),
];
print_r(json_encode($data));
echo "</script>";
Now I want to add another array "itemListElement" inside the last $data['#graph'][] and print but don't know how to go about it.
am expecting
{
"#type": "BreadcrumbList",
"#id": "http:\/\/localhost\/#breadcrumb",
"itemListElement": [{
"#type": "ListItem",
"position": "1",
"item": {
"#id": "http:\/\/localhost",
"name": "Home"
}
}, {
"#type": "ListItem",
"position": "1",
"item": {
"#id": "link 2",
"name": "Home"
}
}]
}
You're referring to nested arrays.
echo '<script type="application/ld+json">';
$data['#graph'][] = [
'#type' => 'BreadcrumbList',
'#id' => "http:\/\/localhost\/#breadcrumb",
'itemListElement' => [
[
'#type' => 'ListItem',
'position' => '1',
'item' => [
'#id' => "http:\/\/localhost",
'name' => 'Home'
]
],
[
'#type' => 'ListItem',
'position' => '2',
'item' => [
'#id' => 'link 2',
'name' => 'Home'
]
]
]
];
print_r(json_encode($data));
echo "</script>";
Good luck on your test
<?php
// PHP program to creating two
// dimensional associative array
$marks = array(
// Ankit will act as key
"Ankit" => array(
// Subject and marks are
// the key value pair
"C" => 95,
"DCO" => 85,
"FOL" => 74,
),
// Ram will act as key
"Ram" => array(
// Subject and marks are
// the key value pair
"C" => 78,
"DCO" => 98,
"FOL" => 46,
),
// Anoop will act as key
"Anoop" => array(
// Subject and marks are
// the key value pair
"C" => 88,
"DCO" => 46,
"FOL" => 99,
),
);
echo "Display Marks: \n";
print_r($marks);
?>
**Output:**
Display Marks:
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
[FOL] => 74
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
[FOL] => 46
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
[FOL] => 99
)`enter code here`
)

Array structure in datatables

How to obtain the following structure after the php json_encode.
It is possible?
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800"
},
{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750"
}
]
}
How must look arrays?
Although formally array keys can only be integer you could simple use:
array( 'data' =>
array(
array( 'name' => 'tiger nixon', 'position' => 'system architect', 'salary' => '$320,800' ),
array( 'name' => 'Garrett Winters', 'position' => 'Accountant', 'salary' => '$170,750' )
)
);

How do I iterate through a JSON array of arrays in CodeIgniter/PHP?

My view is displaying the JSON response. My end goal is to display specific product attributes as well as sub-arrays like product variants within a table.
In RoR I'm accustomed to getting object attributes by doing something like
<% #products.each do |product| %>
<%= product.handle %>
<% end %>
And it's this basic functionality I’m trying to replicate. I’m not sure if I’m doing something wrong with the json_decode method, or if I’m introducing a syntax error when I try to display a particular attribute of an object within the array, or if something else is going on as this is my first time using PHP.
controllers/products.php:
class Products extends CI_Controller {
public function index() {
$token = $this->session->userdata('token');
$this->load->library('shopify', array('shop' => 'boxcetech', 'token' => $token));
$this->load->view('products');
}
}
views/products.php
$products = $this->shopify->getProducts(); // call the getProducts function from my custom Shopify library
libraries/shopify.php
$response = file_get_contents($url, false, $context);
$response = json_decode($response, true);
return $response;
the json
{
"products": [
{
"body_html": "ats descrip",
"created_at": "2014-06-04T15:25:42-04:00",
"handle": "all-terrain-sound",
"id": 303615011,
"product_type": "Electronics",
"published_at": "2014-06-04T15:19:51-04:00",
"published_scope": "global",
"template_suffix": null,
"title": "All-Terrain Sound",
"updated_at": "2014-06-12T10:00:02-04:00",
"vendor": "BOXCeTECH",
"tags": "",
"variants": [
{
"barcode": null,
"compare_at_price": null,
"created_at": "2014-06-04T15:25:42-04:00",
"fulfillment_service": "manual",
"grams": 513,
"id": 708832835,
"inventory_management": null,
"inventory_policy": "deny",
"option1": "Default Title",
"option2": null,
"option3": null,
"position": 1,
"price": "69.95",
"product_id": 303615011,
"requires_shipping": true,
"sku": "ats-1",
"taxable": true,
"title": "Default Title",
"updated_at": "2014-06-04T15:25:42-04:00",
"inventory_quantity": 0,
"old_inventory_quantity": 0
}
],
"options": [
{
"id": 359550119,
"name": "Title",
"position": 1,
"product_id": 303615011
}
],
"images": [
{
"created_at": "2014-06-04T15:25:42-04:00",
"id": 726055931,
"position": 1,
"product_id": 303615011,
"updated_at": "2014-06-04T15:25:42-04:00",
"src": "http://cdn.shopify.com/s/files/1/0525/6049/products/ATS-front.png?v=1401909942"
}
],
"image": {
"created_at": "2014-06-04T15:25:42-04:00",
"id": 726055931,
"position": 1,
"product_id": 303615011,
"updated_at": "2014-06-04T15:25:42-04:00",
"src": "http://cdn.shopify.com/s/files/1/0525/6049/products/ATS-front.png?v=1401909942"
}
}
]
}
output in browser at localhost:8080/products
array (
'products' =>
array (
0 =>
array (
'body_html' => 'ats descrip',
'created_at' => '2014-06-04T15:25:42-04:00',
'handle' => 'all-terrain-sound',
'id' => 303615011,
'product_type' => 'Electronics',
'published_at' => '2014-06-04T15:19:51-04:00',
'published_scope' => 'global',
'template_suffix' => NULL,
'title' => 'All-Terrain Sound',
'updated_at' => '2014-06-12T10:00:02-04:00',
'vendor' => 'BOXCeTECH',
'tags' => '',
'variants' =>
array (
0 =>
array (
'barcode' => NULL,
'compare_at_price' => NULL,
'created_at' => '2014-06-04T15:25:42-04:00',
'fulfillment_service' => 'manual',
'grams' => 513,
'id' => 708832835,
'inventory_management' => NULL,
'inventory_policy' => 'deny',
'option1' => 'Default Title',
'option2' => NULL,
'option3' => NULL,
'position' => 1,
'price' => '69.95',
'product_id' => 303615011,
'requires_shipping' => true,
'sku' => 'ats-1',
'taxable' => true,
'title' => 'Default Title',
'updated_at' => '2014-06-04T15:25:42-04:00',
'inventory_quantity' => 0,
'old_inventory_quantity' => 0,
),
),
'options' =>
array (
0 =>
array (
'id' => 359550119,
'name' => 'Title',
'position' => 1,
'product_id' => 303615011,
),
),
'images' =>
array (
0 =>
array (
'created_at' => '2014-06-04T15:25:42-04:00',
'id' => 726055931,
'position' => 1,
'product_id' => 303615011,
'updated_at' => '2014-06-04T15:25:42-04:00',
'src' => 'http://cdn.shopify.com/s/files/1/0525/6049/products/ATS-front.png?v=1401909942',
),
),
'image' =>
array (
'created_at' => '2014-06-04T15:25:42-04:00',
'id' => 726055931,
'position' => 1,
'product_id' => 303615011,
'updated_at' => '2014-06-04T15:25:42-04:00',
'src' => 'http://cdn.shopify.com/s/files/1/0525/6049/products/ATS-front.png?v=1401909942',
),
),
etc....
),
)
Try this:
foreach($products['products'] as $product){
echo $product['handle']; //will print each product handle
$product_handles[] = $product['handle'] //will create array of product handles
}
Just iterate through the values. You can do this using array_map or foreach. The value of $test_data is the exact JSON sample you posted to your original question:
// Decode the source JSON as an array.
$products_array = json_decode($test_data, true);
// Example with array_map.
function get_product_handles ($data){
return $data['handle'];
}
$product_handles_map = array_map('get_product_handles', $products_array['products']);
// Example with foreach.
$product_handles_array = array();
foreach ($products_array['products'] as $product_key => $product_value) {
$product_handles_array[] = $product_value['handle'];
}
// Outout via array_map.
echo '<b>Outout via array_map:</b>';
echo '<pre>';
print_r($product_handles_map);
echo '</pre>';
// Outout via foreach.
echo '<b>Outout via foreach:</b>';
echo '<pre>';
print_r($product_handles_array);
echo '</pre>';
And here is the output of that:
Outout via array_map:
Array
(
[0] => all-terrain-sound
)
Outout via foreach:
Array
(
[0] => all-terrain-sound
)

MongoDb Aggregate function issue with php

I am new to mongoDb and facing issue in using aggregate function. I am trying to get sum of the fields "expectations" and "overall" but it returns 0. I also want to take the total count of the comments which are not empty or null in the same query.
$out = $collection->aggregate
(
array(
array( '$match' => array( 'id' => 6200 )),
array ('$unwind' => '$reviews'),
array( '$group' => array( '_id' => '$id',
'exptotal' => array( '$sum' => array('reviews' => '$expectations') ),
'total' => array( '$sum' => array('reviews' => '$overall' ) ),
'count' => array( '$sum' => 1 )
)
)
)
);
Here is the json
{
"_id": "528c62406a542f7c6a6bf522",
"id": 6200,
"categories": [
{
"id": 6,
"name": "Artificial Intelligence"
},
{
"id": 5,
"name": "Statistics and Data Analysis"
}
],
"courseId": "COURSE_16",
"institute": {
"id": 5693,
"name": "YZ University"
},
"instructors": [
" A Morris"
],
"language": "en",
"reviews": [
{
"username": "kalis",
"expectations": 3,
"content": 2,
"overall": 3,
"comments": "This is really good course for improvement",
"datecreated": "2013-11-02T17:04:11.102Z"
},
{
"username": "julia",
"expectations": 4,
"content": 2,
"overall": 2,
"comments": "This improves my skill a lot",
"datecreated": "2013-11-03T17:04:11.102Z"
},
{
"username": "john",
"expectations": 2,
"content": 4,
"overall": 4,
"comments": "",
"datecreated": "2013-11-04T17:04:11.102Z"
}
],
"shortName": "ml",
"title": "Machine Learning"
}
This looks like it would work:
$out = $collection->aggregate(array(
array('$match' => array( 'id' => 6200 )),
array ('$unwind' => '$reviews'),
array('$unwind' => '$comments'),
array( '$group' => array( '_id' => '$id',
'commTotal' => array('$sum' => array('$cond'=>array(array('$eq'=>array('$comments',null),0,1)))),
'exptotal' => array( '$sum' => '$reviews.expectations'),
'total' => array( '$sum' => '$reviews.overall' ),
'count' => array( '$sum' => 1 )
))
));
The reason is that when you $unwind the data is still in its subdocument field it is just that the subdocument has become an object of a single review.
The documentation is a little misleading on this operator I'll give you that.

Categories