Converting a PHP array into a table in html [closed] - php

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 } ?>
...

Related

Dynamic array into a static array

I have this static code today that works fine, now i need to make the
order line dynamic. The code is from a e-commerce store.
$order = [
"purchase_country" => "SE",
"purchase_currency" => "SEK",
"locale" => "sv-SE",
"order_amount" => 10000,
"order_tax_amount" => 2000,
"order_lines" => [
[
"type" => "physical",
"reference" => "123050",
"name" => "Tomatoes",
"quantity" => 10,
"quantity_unit" => "kg",
"unit_price" => 600,
"tax_rate" => 2500,
"total_amount" => 6000,
"total_tax_amount" => 1200
],
[
"type" => "physical",
"reference" => "543670",
"name" => "Bananas",
"quantity" => 1,
"quantity_unit" => "bag",
"unit_price" => 5000,
"tax_rate" => 2500,
"total_amount" => 4000,
"total_discount_amount" => 1000,
"total_tax_amount" => 800
]
],
"merchant_urls" => [
"terms" => "https://www.example.com/villkor.php",
"cancellation_terms" => "https://www.example.com/terms/cancellation.html",
"checkout" => "https://www.example.com/_script/checkout.php",
"confirmation" => "https://www.example.com/_script/checkout.php",
// Callbacks
"push" => "https://www.example.com/api/push",
"validation" => "https://www.example.com/api/validation",
"shipping_option_update" => "https://www.example.com/api/shipment",
"address_update" => "https://www.example.com/api/address",
"notification" => "https://www.example.com/api/pending",
"country_change" => "https://www.example.com/api/country"
]
];
Now I need to make order_lines dynamic.
I have tried this code:
$order = [
"purchase_country" => "SE",
"purchase_currency" => "SEK",
"locale" => "sv-SE",
"order_amount" => 10000,
"order_tax_amount" => 2000,
"order_lines" => [
$cartsql="select a, b, c, d from lux_cart WHERE status = 0 ORDER BY a DESC";
if ($result=mysqli_query($mysqli,$cartsql)){
while ($cartrow=mysqli_fetch_row($result)){
$itemid = $cartrow[0];
$prodTitel = $cartrow[1];
$antalcart = $cartrow[2];
$prodPris = $cartrow[3];
[
"type" => "physical",
"reference" => "$itemid",
"name" => "$prodTitel",
"quantity" => $antalcart,
"unit_price" => $prodPris,
"tax_rate" => 2500,
"total_amount" => $prodPris,
"total_tax_amount" => 1200
],
}
}
"merchant_urls" => [
"terms" => "https://www.example.com/villkor.php",
"cancellation_terms" => "https://www.example.com/terms/cancellation.html",
"checkout" => "https://www.example.com/_script/checkout.php",
"confirmation" => "https://www.example.com/_script/checkout.php",
// Callbacks
"push" => "https://www.example.com/api/push",
"validation" => "https://www.example.com/api/validation",
"shipping_option_update" => "https://www.example.com/api/shipment",
"address_update" => "https://www.example.com/api/address",
"notification" => "https://www.example.com/api/pending",
"country_change" => "https://www.example.com/api/country"
]
];
But the page broken without any error message. I think I need to make some array ore something to resolve this issue. Can someone help me figure out what I am doing wrong here?
You can't execute PHP code inside an array definition like that. That's causing a parse error that's the reason your page is broken with no error. (You can change settings on your development server to show these errors as well.) Instead, define the array with an empty array for order_lines
$order = [
"purchase_country" => "SE",
"purchase_currency" => "SEK",
"locale" => "sv-SE",
"order_amount" => 10000,
"order_tax_amount" => 2000,
"order_lines" => [],
"merchant_urls" => [
"terms" => "https://www.example.com/villkor.php",
"cancellation_terms" => "https://www.example.com/terms/cancellation.html",
"checkout" => "https://www.example.com/_script/checkout.php",
"confirmation" => "https://www.example.com/_script/checkout.php",
// Callbacks
"push" => "https://www.example.com/api/push",
"validation" => "https://www.example.com/api/validation",
"shipping_option_update" => "https://www.example.com/api/shipment",
"address_update" => "https://www.example.com/api/address",
"notification" => "https://www.example.com/api/pending",
"country_change" => "https://www.example.com/api/country"
]
];
Then fill that key with values from your query.
$cartsql="select a, b, c, d from lux_cart WHERE status = 0 ORDER BY a DESC";
if ($result=mysqli_query($mysqli,$cartsql)){
while ($cartrow=mysqli_fetch_row($result)){
$itemid = $cartrow[0];
$prodTitel = $cartrow[1];
$antalcart = $cartrow[2];
$prodPris = $cartrow[3];
// Use [] to append the rows to the existing key
$order['order_lines'][] = [
"type" => "physical",
"reference" => "$itemid",
"name" => "$prodTitel",
"quantity" => $antalcart,
"unit_price" => $prodPris,
"tax_rate" => 2500,
"total_amount" => $prodPris,
"total_tax_amount" => 1200
];
}
}

search for a value array in array in php

In my program i have arrays in the following format . I need to find whether a value is present in an the array
return [
"affiliates" => [
"name" => 'Affiliates',
"value" => 11
],
"business" => [
"name" => 'Business',
"value" => 12
],
"inquiries" => [
"name" => 'Inquiries',
"value" => 13
],
"students" => [
"name" => 'Students',
"value" => 14
],
"teachers" => [
"name" => 'Teachers',
"value" => 15
],
"Personal" => [
"name" => 'Personal',
"value" => 3
],
];
I am doing the following. I am expecting that the search will find the value(12) which is a business, but It is returning false.
$searchcategoryid = '12';
$key = array_search($searchcategoryid, array_column(config('peopletypes.students'), 'value'));
Please note that config('peopletypes.students')will return the array above mentioned. I am using laravel.
You have some sort of configuration problem, this code prints 1.
<?php
$searchcategoryid = '12';
$key = array_search($searchcategoryid, array_column([
"affiliates" => [
"name" => 'Affiliates',
"value" => 11
],
"business" => [
"name" => 'Business',
"value" => 12
],
"inquiries" => [
"name" => 'Inquiries',
"value" => 13
],
"students" => [
"name" => 'Students',
"value" => 14
],
"teachers" => [
"name" => 'Teachers',
"value" => 15
],
"Personal" => [
"name" => 'Personal',
"value" => 3
],
], 'value'));
echo $key;
Try to make sure that your config function actually returns the array you claim it to.

How to group and sum subarray items in PHP Laravel

I have N arrays. with n grade_items subarrays.
just like this.
array:2 [
0 => array:10 [
"id" => 9
"course_id" => 6
"semester_id" => 2
"name" => "Assignment"
"total_score" => 10
"grade_items" => array:1 [
0 => array:7 [
"id" => 5
"gradelist_id" => 9
"student_course_id" => 11
"score" => 8
"created_at" => "2020-04-21T03:31:20.000000Z"
"updated_at" => "2020-04-21T20:04:10.000000Z"
]
]
]
1 => array:10 [
"id" => 10
"course_id" => 6
"semester_id" => 2
"name" => "Pop Quiz"
"total_score" => 20
"grade_items" => array:1 [
0 => array:7 [
"id" => 6
"gradelist_id" => 10
"student_course_id" => 11
"score" => null
"created_at" => "2020-04-22T00:11:17.000000Z"
"updated_at" => "2020-04-22T00:11:17.000000Z"
]
]
]
]
I am trying to add each grade_item subarray from each array where the student_course_id is the same. Where there is only one grade_item and no other one with the same student_course_id, then it returns just that one value instead of a sum.
I have gone through this thread
But it just messed up the logic in my head further. I've been at this for weeks.
When I add the scores from each grade_item, i want to put that value into another model say "result_model" that would look like:
result_item [
"id" => 1,
"student_course_id" => 11,
"score" => 15 //total of grade_items from all arrays where the student_course_id's were the same
];
Help!
So basically you want to regroup the current information to receive the sum of grades. It seems the the information comes form a databases, so why don't you GROUP BY and sum on database level?
Anyway. Here's an approach. Start by keeping a map of student_course_id => score. First it will be empty: $map = [];
Then start iterating through the whole structure e.g. foreach ($data as $row. For each row, you need to check all the corresponding grade_items e.g. foreach ($row['grade_items'] as $gradeItem). Now you need to check whether the student_course_id from the grade item is present into the mapping.
If it's not present, create it with starting value of zero e.g.
if (!key_exists($gradeItem['student_course_id'], $map)) {
$map[$gradeItem['student_course_id']] = 0;
}
Once you ensure that the student_course_id is present, you can just add to the previous value the current score => $map[$gradeItem['student_course_id']] += $gradeItem['score'].
Here is a sample data i used
$array = [
[
'id' => 9,
'course_id' => 6,
'semester_id' => 2,
'name' => 'Assignment',
'total_score' => 10,
'grade_items' => [
[
'id' => 5,
'gradelist_id' => 9,
'student_course_id' => 11,
'score' => 8,
'created_at' => '2020-04-21T03:31:20.000000Z',
'updated_at' => '2020-04-21T20:04:10.000000Z',
],
[
'id' => 5,
'gradelist_id' => 9,
'student_course_id' => 15,
'score' => 15,
'created_at' => '2020-04-21T03:31:20.000000Z',
'updated_at' => '2020-04-21T20:04:10.000000Z',
]
]
],
[
'id' => 10,
'course_id' => 6,
'semester_id' => 2,
'name' => 'Pop Quiz',
'total_score' => 20,
'grade_items' => [
[
'id' => 6,
'gradelist_id' => 10,
'student_course_id' => 11,
'score' => 21,
'created_at' => '2020-04-22T00:11:17.000000Z',
'updated_at' => '2020-04-22T00:11:17.000000Z',
],
[
'id' => 6,
'gradelist_id' => 10,
'student_course_id' => 23,
'score' => 15,
'created_at' => '2020-04-22T00:11:17.000000Z',
'updated_at' => '2020-04-22T00:11:17.000000Z',
]
]
]
];
and here is the code;
$id = 0;
return collect($array)
->flatMap(function ($item){
return $item['grade_items'];
})
->groupBy('student_course_id')
->transform(function ($subItems, $courseId) use (&$id) {
$id++;
return [
'id' => $id,
'student_course_id' => $courseId,
'score' => $subItems->sum('score')
];
})
->values()
->toArray();
here is the result;
[
[
'id' => 1,
'student_course_id' => 11,
'score' => 29,
],
[
'id' => 2,
'student_course_id' => 15,
'score' => 15,
],
[
'id' => 3,
'student_course_id' => 23,
'score' => 15,
]
]
Use the sum() function. You can loop through the array, and do any checks you need, like if it is not Null etc, and pluck() it and then sum() it.
May I suggest recursivity approach?
<?php
function rec_sum_grades(&$array_grades, &$sum = 0){
$sum += $array_grades['total_score'];
if(!empty($array_grades['grade_items'])){
$this->rec_sum_grades($array_grades['grade_items'], $sum);
}
}
rec_sum_grades($array_grades, $sum);
echo $sum;
?>

how to setup arrays to result to this json encoded format

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
]

Merge two pairs in the same array if the pairs have the same value

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

Categories