Push nested element into multidimensional array [duplicate] - php

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`
)

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);

php array of categories from products

I have an array
$catname = Array
(
[0] => Array
(
[id] => 39
[name] => Football
[votes] => 3
[ndate] => 01-2021
)
[1] => Array
(
[id] => 38
[name] => Rugby
[votes] => 2
[ndate] => 01-2021
)
[2] => Array
(
[id] => 39
[name] => Football
[votes] => 1
[ndate] => 02-2021
)
[3] => Array
(
[id] => 38
[name] => Rugby
[votes] => 1
[ndate] => 02-2021
)
)
I want to group them by name, so the desired JSON output wants t to be like this
array =[{
name: football,
id:39,
data: [
{date: 01-2021, votes: 3},
{date: 02-2021, votes: 2},
{date: 03-2021, votes: 1},
]
},
name: Rugby,
id:38,
data: [
{date: 01-2021, votes: 2},
{date: 02-2021, votes: 2},
{date: 03-2021, votes: 0},
]
}
]
So far I did this
$itemsByCategory = array();
foreach($catname as $item){
$optionname = $item['name'];
$vote = $item['votes'];
$dates = $item['ndate'];
if (!array_key_exists($optionname, $itemsByCategory))
$itemsByCategory[$item['name']][] = array(
'vote' =>$vote,
'date' =>$dates
);
}
But doesn't produce the desired result. I also tried with if (array_key_exists but still not been able to think, what's wrong with thsi code. Any suggestions?
<?php
$catname = [
[
'id' => 39,
'name' => 'Football',
'votes' => 3,
'ndate' => '01-2021',
],
[
'id' => 38,
'name' => 'Rugby',
'votes' => 2,
'ndate' => '01-2021',
],
[
'id' => 39,
'name' => 'Football',
'votes' => 1,
'ndate' => '02-2021',
],
[
'id' => 38,
'name' => 'Rugby',
'votes' => 1,
'ndate' => '02-2021',
],
];
$grouped = [];
foreach($catname as $cat) {
$id = $cat['id'];
$name = $cat['name'];
$votes = $cat['votes'];
$ndate = $cat['ndate'];
if(!isset($grouped[$id])) {
$grouped[$id] = [
'name' => $name,
'id' => $id,
'data' => []
];
}
$grouped[$id]['data'][] = [
'votes' => $votes,
'date' => $ndate,
];
}
echo json_encode(array_values($grouped));
->
[
{
"name": "Football",
"id": 39,
"data": [
{
"votes": 3,
"date": "01-2021"
},
{
"votes": 1,
"date": "02-2021"
}
]
},
{
"name": "Rugby",
"id": 38,
"data": [
{
"votes": 2,
"date": "01-2021"
},
{
"votes": 1,
"date": "02-2021"
}
]
}
]
You forgot about 2nd level of the array. Try the following:
$itemsByCategory = [];
foreach($catname as $item) {
$optionname = $item['name'];
$vote = $item['votes'];
$dates = $item['ndate'];
if (!array_key_exists($optionname, $itemsByCategory)) {
$itemsByCategory[$optionname][] = [
'name' => $optionname,
'id' => $item['id'],
'data' => [],
];
}
$itemsByCategory[$optionname]['data'][] = [
'vote' => $vote,
'date' => $dates,
];
}

How to mutate this array within `array_reduce`

Is there a way to mutate an array using array_reduce in PHP?
I'm trying to do something like this:
Given some ordered list of ids:
$array = [["id" => 1], ["id" => 13], ["id" => 4]];
And a tree that has a subtree matching the corresponding ids:
$tree = [
"id" => 2334,
"children" => [
[
"id" => 111,
"children" => []
],
[
"id" => 1, // <- this is a match
"children" => [
[
"id" => 13, // <- this is a match
"children" => [
[
"id" => 4, // <- this is a match
"children" => []
],
[
"id" => 225893,
"children" => []
],
[
"id" => 225902,
"children" => []
]
]
]
]
]
]
];
How can I mutate the arrays in that subtree?
I'm currently trying to use array_reduce to walk down the tree and mutate it. However, the mutation isn't being applied to the originally passed in $tree.
array_reduce($array, function (&$acc, $item) {
$index = array_search($item['id'], array_column($acc['children'], 'id'));
$acc['children'][$index]['mutated'] = true; // mutation here
return $acc['children'][$index];
}, $tree);
echo "<pre>";
var_dump($tree); // $tree is unchanged here
echo "</pre>";
Why is $tree not mutated after the running above array_reduce?
Is there a way to use foreach in this case?
I think this function will do what you want. It recurses down $tree, looking for id values that are in $array and setting the mutation flag for those children:
function mutate(&$tree, $array) {
if (in_array($tree['id'], array_column($array, 'id'))) {
$tree['mutated'] = true;
}
foreach ($tree['children'] as &$child) {
mutate($child, $array);
}
}
mutate($tree, $array);
var_export($tree);
Output:
array (
'id' => 2334,
'children' => array (
0 => array (
'id' => 111,
'children' => array ( ),
),
1 => array (
'id' => 1,
'children' => array (
0 => array (
'id' => 13,
'children' => array (
0 => array (
'id' => 4,
'children' => array ( ),
'mutated' => true,
),
1 => array (
'id' => 225893,
'children' => array ( ),
),
2 => array (
'id' => 225902,
'children' => array ( ),
),
),
'mutated' => true,
),
),
'mutated' => true,
),
),
)
Demo on 3v4l.org

building a php array that will make specific JSON

I need to generate the following JSON:
{
"title": "my form",
"fields": [
{
"type": "short_text",
"question": "What is your name?"
},
{
"type": "multiple_choice",
"question": "How often do you want to receive emails?",
"choices": [
{
"label": "Daily"
},
{
"label": "Weekly"
},
{
"label": "Monthly"
},]
},]
I'm trying to do it with this php code:
$data = array(
"title" => "my form",
"fields" => array (
array (
"type" => "short_text",
"question" => "What is your name?"
),
array (
array (
"type" => "multiple_choice",
"question" => "How often do you want to receive emails?",
"choices" => (
array ("label" => "Daily")
),
(array ("label" => "Weekly")),
(array ("label" => "Monthly"))
)
)
)
);
$output = json_encode($data);
...but it's not working.
I'd appreciate any help you guys can offer!
<?php
$data = array (
'title' => 'my form',
'fields' =>
array (
array (
'type' => 'short_text',
'question' => 'What is your name?',
),
array (
'type' => 'multiple_choice',
'question' => 'How often do you want to receive emails?',
'choices' =>
array (
array (
'label' => 'Daily',
),
array (
'label' => 'Weekly',
),
array (
'label' => 'Monthly',
),
),
),
),
);
$output = json_encode($data);
?>

converting multidimensional array into json

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']);

Categories