how do I setup my arrays wherein when I call json_encode, it returns a result like this?
{
"rows":[
{"id":1,"name":"Chai","price":18.00},
{"id":2,"name":"Chang","price":19.00},
{"id":3,"name":"Aniseed Syrup","price":10.00},
{"id":4,"name":"Chef Anton's Cajun Seasoning","price":22.00},
{"id":5,"name":"Chef Anton's Gumbo Mix","price":21.35},
{"id":6,"name":"Grandma's Boysenberry Spread","price":25.00},
{"id":7,"name":"Uncle Bob's Organic Dried Pears","price":30.00},
{"id":8,"name":"Northwoods Cranberry Sauce","price":40.00},
{"id":9,"name":"Mishi Kobe Niku","price":97.00}
],
"footer":[
{"name":"Total","price":282.35}
]
}
I need to get 2 result sets, one for the actual rows and one for the sum of all the rows. I both convert them to arrays and combine them to be encoded to json, for consumption on the web page.
But in the end I would like to format them that way when I encode in json, it returns the format above. But when I try to join them, it appears the arrays get one dimension deeper. And this can't be read by easyUI.
json_encode([
'rows' => [
["id" => 1, "name" => "Chai", "price" => 18.00],
["id" => 2, "name" => "Chang", "price" => 19.00],
["id" => 3, "name" => "Aniseed Syrup", "price" => 10.00],
["id" => 4, "name" => "Chef Anton's Cajun Seasoning", "price" => 22.00],
["id" => 5, "name" => "Chef Anton's Gumbo Mix", "price" => 21.35],
["id" => 6, "name" => "Grandma's Boysenberry Spread", "price" => 25.00],
["id" => 7, "name" => "Uncle Bob's Organic Dried Pears", "price" => 30.00],
["id" => 8, "name" => "Northwoods Cranberry Sauce", "price" => 40.00],
["id" => 9, "name" => "Mishi Kobe Niku", "price" => 97.00]
],
'footer' => [
[
'name' => 'Total',
'price' => 282.35
]
]
]);
This will give you the structure you're asking for, although it seems like the footer doesn't need to be an array like you have it in your question, which I assume is what you mean by it being one dimension deeper than necessary, in which case that part would instead be:
'footer' => [
'name' => 'Total',
'price' => 282.35
]
Related
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);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am new to PHP and I have dabbled with basic arrays from the video tutorials. I need some help in converting a PHP multidimensional array into a HTML table. I have already wasted a bunch of time in trying to get in the format I wanted, and thought someone in this forum will have an easy and better answer for me. Thank you before hand.
Here is the PHP array format -
[ ["term" => 3, "val" => 0.7, "user" => ["name" => "user1"], "dept" => ["dep" => "dept1"]],
["term" => 3, "val" => 0.6, "user" => ["name" => "user1"], "dept" => ["dep" => "dept1"]],
["term" => 12, "val" => 0.5, "user" => ["name" => "user1"], "dept" => ["dep" => "dept1"]],
["term" => 3, "val" => 0.1, "user" => ["name" => "user2"], "dept" => ["dep" => "dept1"]],
["term" => 6, "val" => 0.2, "user" => ["name" => "user2"], "dept" => ["dep" => "dept1"]],
["term" => 9, "val" => 0.3, "user" => ["name" => "user2"], "dept" => ["dep" => "dept1"]],
["term" => 3, "val" => 0.4, "user" => ["name" => "user3"], "dept" => ["dep" => "dept1"]],
["term" => 6, "val" => 0.5, "user" => ["name" => "user3"], "dept" => ["dep" => "dept1"]],
["term" => 12, "val" => 0.6, "user" => ["name" => "user3"], "dept" => ["dep" => "dept1"]]
]
and here is the out put format I am looking for -
Basically, the table should list all the users along the rows and the columns should be the unique values of the 'terms' in the array. the values in the table should be field 'val'. In case there are multiple values for 'val', then it should be the maximum value of the 'val'.
I hope I was clear in my q. I look forward for your help.
I would suggest transforming your array first so that it is grouped by the user so that you can loop more sensibly. Essentially you would end up with:
[
[
"user" => [
"name" => "user1"
],
"terms" => [
"3" => 1,
"6" => 0,
"9" => 0,
"12" => 0
]
],
[
"user" => [
"name" => "user2"
]
"terms" => [ ... ]
]
]
From there, it's easy to loop through each user and output the relevant data
...
# in your HTML file
<?php foreach($users_data as $user_data){ ?>
<tr>
<td><?php echo $user_data["user"]["name"]; ?></td>
<td><?php echo $user_data["terms"]["3"]; ?></td>
<td><?php echo $user_data["terms"]["6"]; ?></td>
<td><?php echo $user_data["terms"]["9"]; ?></td>
<td><?php echo $user_data["terms"]["12"]; ?></td>
</tr>
<?php } ?>
...
I'm creating a Google Sheet adding content like: =HYPERLINK("https://example.com","Example")
Which works fine until I try to alter the cell -> userEnteredFormat -> textFormat
Here's an example of broken links
Cell formatting works (see the second sheet).
If I change my config from
"cell" => [
"userEnteredFormat" => [
"backgroundColor" => [
"red" => 1.0,
"green" => 1.0,
"blue" => 1.0
],
"horizontalAlignment" => "LEFT",
"wrapStrategy" => "WRAP",
"textFormat" => [
"foregroundColor" => [
"red" => 0.0,
"green" => 0.0,
"blue" => 0.5
],
"fontSize" => 10,
"bold" => true
]
]
],
"fields" => "userEnteredFormat(backgroundColor,textFormat,horizontalAlignment,wrapStrategy)"
To
"cell" => [
"userEnteredFormat" => [
"backgroundColor" => [
"red" => 1.0,
"green" => 1.0,
"blue" => 1.0
],
"horizontalAlignment" => "LEFT",
"wrapStrategy" => "WRAP",
"textFormat" => [
]
]
],
"fields" => "userEnteredFormat(backgroundColor,textFormat,horizontalAlignment,wrapStrategy)"
The issue goes away.
I thought that from your request body, I thought that the reason of your issue might be due to fields. So, in your situation, how about modifying the value of fields as follows?
From:
"fields" => "userEnteredFormat(backgroundColor,textFormat,horizontalAlignment,wrapStrategy)"
To:
"fields" => "userEnteredFormat(backgroundColor,textFormat(foregroundColor,fontSize,bold),horizontalAlignment,wrapStrategy)"
Reference:
Method: spreadsheets.batchUpdate
Looks like I am probably having a dumb moment here. I have got a collection that I am trying to filter on basis of couple of conditions. Here is the array:
$files =[
[
"customisation_id" => "2357323",
"file_type" => 2,
"url" => "transparent/76caa009d0c2aa32793a8f48ad395dcb_616351.png.png"
],
[
"customisation_id" => "2357323",
"file_type" => 3,
"url" => "nonTransparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.png"
],
[
"customisation_id" => "2357324",
"file_type" => 2,
"url" => "transparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.gif"
],
[
"customisation_id" => "2357324",
"file_type" => 3,
"url" => "nonTransparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.png"
],
[
"customisation_id" => "2357350",
"file_type" => 2,
"url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
],
[
"customisation_id" => "2357355",
"file_type" => 3,
"url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
]
];
I would like to create a new array out of it which has a file_type of 2 with no duplicate records with same customisation_id. However, if there isn't a repeating record in terms of customer_id then just add it to collection. NOTE: I am using arrays interchangeably with
collection as I am going to use collection for it. Ideally, I want a new array or collection with following structure:
$files =[
[
"customisation_id" => "2357323",
"file_type" => 2,
"url" => "transparent/76caa009d0c2aa32793a8f48ad395dcb_616351.png.png"
],
[
"customisation_id" => "2357324",
"file_type" => 2,
"url" => "transparent/5ae5a3ec64a35ebcaa26e211244c24a4_826308.jpg.gif"
],
[
"customisation_id" => "2357350",
"file_type" => 2,
"url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
],
[
"customisation_id" => "2357355",
"file_type" => 3,
"url" => "transparent/64dc36fc492a87cf96f1fd2346e60dd3_560667.jpg.gif"
]
];
I have already tried filter, map and reduce methods of collection which solves the first part of puzzle but then I get stuck with second condition.
Thank you!
$newArray = collect($files)->unique('customisation_id')->values()->all();
You should also read about intersect() : https://laravel.com/docs/6.x/collections#method-intersect
I have the following pairs and they are in the same array:
[
["ID" => 0, "User" => "Test" , "Type" => 3, "Target" => "Caris"],
["ID" => 1, "User" => "Test1", "Type" => 3, "Target" => "Caris"],
["ID" => 2, "User" => "Test2", "Type" => 4, "Target" => "Shirone"],
["ID" => 3, "User" => "Test3", "Type" => 3, "Target" => "Caris"]
]
I want to get the kinds of them, so I using the following code:
$SortList = [];
foreach($Notif as $Key => $Value)
array_push($SortList, ['Type' => $Value['Type'],
'Target' => $Value['Target']]);
and get this:
[
["Type" => 3, "Target" => "Caris"],
["Type" => 3, "Target" => "Caris"],
["Type" => 4, "Target" => "Shirone"],
["Type" => 3, "Target" => "Caris"]
]
But what I really want is something like this:
[
["Type" => 3, "Target" => "Caris"],
["Type" => 4, "Target" => "Shirone"]
]
I want to merge the pairs if they were same value,
(array_merge() seems can only used for non-pair)
How can I merge them like something above?
$SortList = [];
foreach($Notif as $Key => $Value) {
// Just save only value for the same pair, use them concatenated as the key
$SortList[$Value['Type']."_".$Value['Target']] =
array('Type' => $Value['Type'], 'Target' => $Value['Target']);
}
// remove extra stuff (the keys) that was added to prevent duplicates
$SortList = array_values($SortList);