Array to table HTML output - php

i have a question here...
i have an array from mysql like this...
array(3) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["name"]=>
string(8) "Delivery"
["namaShipp"]=>
string(3) "JNE"
["price"]=>
string(5) "30000"
}
[1]=>
array(4) {
["id"]=>
string(1) "3"
["name"]=>
string(12) "Installation"
["namaShipp"]=>
string(7) "Kudamas"
["price"]=>
string(1) "0"
}
[2]=>
array(4) {
["id"]=>
string(1) "5"
["name"]=>
string(12) "Installation"
["namaShipp"]=>
string(5) "MTECH"
["price"]=>
string(1) "0"
}
}
and then i want output it to a simple table.. and i dont know how..
So the result is grouped by ['name'] key.
My question is how to output that array to become like this
-----------------------------
INSTALLATION (get from ['name'])
----------------------------
MTECH - 0 <---- MTECH is get from ['namaShipp'] and 0 is from ['price']
KUDAMAS - 0
-----------------------------
DELIVERY
-----------------------------
JNE - 30000
Anybody can help please?? i will appreciate that..
i've just very confused about thisss...
thanks before

Something like this:
$current=false;
foreach($result as $item)
{
if($item['name']!==$current)
{
echo '
---------------------
'.$item['name'].'
---------------------';
$current=$item['name'];
}
echo '
'$item['namaShipp'].' - '.$item['price'];
}

Try this (assuming your array you showed is $processedArray):
$processedArray = array();
foreach ($mainArray as $innerArray) {
$processedArray[$innerArray['name']][] = $innerArray;
}
foreach ($processedArray as $name => $itemsArray) {
echo '----<br />'.$name.'<br />---';
foreach ($itemsArray as $item) {
echo $item['namaShipp'].' - '.$item['price'].'<br />';
}
}

Transform your array! Create an array of arrays of records:
$list=array();
foreach($data as $item)
$list[$item['name']][]=$item;
foreach($list as $groupname=>$records){
echo '--------------- '.$groupname.' ------------';
foreach($records as $item){
//output one $item as before...
}
}

Related

Array data manipulations PHP

I get from my DB data in format like this:
array(12) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "78984"
["month"]=>
string(1) "6"
["hours"]=>
string(10) "10580.0833"
}
[1]=>
array(4) {
["id"]=>
string(1) "2"
["count"]=>
string(5) "64174"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "6866.8333"
}
[2]=>
array(4) {
["id"]=>
string(1) "3"
["count"]=>
string(5) "31032"
["month"]=>
string(1) "6"
["hours"]=>
string(9) "3700.9167"
}
[3]=>
array(4) {
["id"]=>
string(1) "1"
["count"]=>
string(5) "91114"
["month"]=>
string(1) "7"
["hours"]=>
string(10) "11859.6000"
}
...
Each of array inside has a key: "id". It mostly look values from 1 to 3. I would like to create a new array based on this "ids" that would look like this:
array("number of unique ids") {
[0]=> "for id = 0"
array(12) {
int() count/hours
int() count/hours
int() count/hours
...
}
[1]=> "for id = 1 and so on..."
array(12){
....
}
I`ve been trying to do it like this:
$data1 = [];
$data2 = [];
$data3 = [];
foreach($data as $key => $record){
if($record['id'] == 1){
array_push($data1, $record['count']/$record['hours']);
}else if($data['id_zmiana'] == 2){
array_push($data2, $record['count']/$record['hours']);
}else{
array_push($data3, $record['count']/$record['hours']);
}
}
$raport = array_merge($data1, $data2, $data3);
And that would work, but it doesn`t look good in my opinion, beacuse what if the id change to some big number.
Yeah, having separate arrays for each ID is not a good idea. How about:
$raport = [];
foreach ($data as $record) {
$raport[$record['id']][] = $record['count'] / $record['hours']);
}
Simple, and straight to the point.
Haven't tested it. Next time try to use var_export() to export the data you put in your question. That way we can actually use it, without having to rewrite it completely.

PHP Multudimensional Array foreach

Using PHP and MySQL, I have generated an array called $response.
A var_dump of $response can be seen here.
array(2) {
["OperationRequest"]=>
array(4) {
["HTTPHeaders"]=>
array(1) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "UserAgent"
["Value"]=>
string(14) "ApaiIO [2.1.0]"
}
}
}
["RequestId"]=>
string(36) "f53f381e-efb3-4fef-8e39-4f732b4b463e"
["Arguments"]=>
array(1) {
["Argument"]=>
array(11) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(14) "AWSAccessKeyId"
["Value"]=>
string(20) "KEY"
}
}
[1]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(12) "AssociateTag"
["Value"]=>
string(11) "TAG"
}
}
[2]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "IdType"
["Value"]=>
string(4) "ISBN"
}
}
[3]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "ItemId"
["Value"]=>
string(38) "0751538310,9780141382067,9781305341141"
}
}
[4]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "Operation"
["Value"]=>
string(10) "ItemLookup"
}
}.......so on
A json_encode of the array can be seen here (as requested in a comment).
I'd like to select the Title from these two items. From what I can see this is located at;
Items > Item > ItemAttributes > Author
So, using a foreach loop I have tried the following;
foreach ($response as $item) {
echo $item['Items']['Item']['ItemAttributes']['Title']; // line 2
}
However this returns the following error;
Message: Undefined index: Items. Line Number: 2
Where am I going wrong and what must I change in my code in order to achieve the desired result?
Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Thanks
Try this one, it will help you out. You were are iterating on the wrong key that's why you were not getting desired output.
Try this code snippet herefrom json provide by OP in question
foreach($array["Items"]["Item"] as $key => $value)
{
print_r($value["ItemAttributes"]["Title"]);
echo PHP_EOL;
}
Output:
Panic
Panic
Captain Flinn and the Pirate Dinosaurs: Missing Treasure! (Captain Flinn)
For getting unique titles:
foreach(json_decode($json,true)["Items"]["Item"] as $key => $value)
{
$result[]=$value["ItemAttributes"]["Title"];
echo PHP_EOL;
}
print_r(array_unique($result));
#Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Post your encoded json string to
http://json.parser.online.fr
"+" and "-" button at the right panel should help you read it easily.
//Check Items is not empty
if( !isset($response["Items"]["Item"]) || empty($response["Items"]["Item"]) )
throw New Exception("Empty Item");
foreach($response["Items"]["Item"] as $item){
$title = $item['ItemAttributes']['Title']
}
You should debug as:
foreach ($response as $key => $item) {
if(isset($item['Items'])){ //Check Items index defined
echo $item['Items']['Item']['ItemAttributes']['Title'];
}else{
var_dump($key);
}
}

Show only unique values from Array

I have the following array in php:
array(12) {
[0]=>
array(2) {
["adress"]=>
string(17) "Kungsvägen 118 A "
["dob"]=>
string(10) "1969-06-17"
}
[1]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1969-06-17"
}
[2]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1980-05-22"
}
[3]=>
array(2) {
["adress"]=>
string(12) "Myntvägen 8 "
["dob"]=>
string(10) "1980-05-22"
}
[4]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1993-05-09"
}
[5]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1989-06-28"
}
[6]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1991-03-17"
}
[7]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1989-10-30"
}
[8]=>
array(2) {
["adress"]=>
string(23) "Gasslanda VÄSTERGÅRD 2 "
["dob"]=>
string(10) "1980-10-30"
}
[9]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1980-10-30"
}
[10]=>
array(2) {
["adress"]=>
string(14) "Skolgatan 1 B "
["dob"]=>
string(10) "1990-05-01"
}
[11]=>
array(2) {
["adress"]=>
string(11) "Ågatan 6 A "
["dob"]=>
string(10) "1990-05-01"
}
}
I want to print out the unique adress-values in this array when I'm doing an foreach. As you can see, Skolgatan 1 B appears several times in the array, so I want to print it out just once in my loop. How can I do this? I have tried
array_unique([$newArray['adress']);
but that does not work.
$unique = array();
foreach($array as $item)
$unique[$item['adress']] = $item;
Then use $unique
Something like this should work:
$printed_vals = array();
foreach ($array as $item) {
if (!in_array($item['adress'], $printed_vals)) {
print_r($item);
$printed_vals[] = $item['adress'];
}
}
This is how I would have solved this problem. Hope it helps.
$non_duplicates = array();
$i=0;
foreach( $addresses AS $address ){
if( !in_array( $address['adress'], $non_duplicates ) ){
// Use one of the below array_push statements
array_push( $non_duplicates, $i ); // if you want to get the array key position
array_push( $non_duplicates, $address['adress'] ); // if you only want a new array of unique addresses
}
$i++;
}
If you have chosen to only return key positions to $non_duplicates yo can then retrieve your unique positions from you array by:
foreach( $non_duplicates AS $key ){
echo $addresses[$key];
}
I guess you want to print address once but dob in multiple times.. in that case you can do something like followings
$printed_vals = array();
foreach ($array as $item) {
$printed_vals[$item['adress']][] = $item['dob'];
}
foreach ($printed_vals as $address => $values) {
echo $address . " => " . implode(",", $values);
}

create ul and li using a multidimensional array in php

I have the following array:
$tree_array
When I do a var_dump, I get:
array(6) {
[0]=> string(23) "$100,000 Cash Flow 2013"
[1]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(13) "Sell Iron Oak" ["Opportunity"]=> string(13) "Sell Iron Oak"
[2]=> string(2) "10" ["OID"]=> string(2) "10"
}
[2]=> array(2) {
[0]=> string(32) "ask her if she would like to buy" ["Activity"]=> string(32) "ask her if she would like to buy"
}
[3]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(8) "Sell Car" ["Opportunity"]=> string(8) "Sell Car"
[2]=> string(2) "11" ["OID"]=> string(2) "11"
}
[4]=> array(2) {
[0]=> string(52) "Call Roy back to see if he would like to purchase it" ["Activity"]=> string(52) "Call Roy back to see if he would like to purchase it"
}
[5]=> array(1) {
["tot_opp"]=> NULL
}
}
My end goal is to create unordered lists and lists (ul, li) with this data. There will be more data added to the array as the database gets updated, so it will keep growing. My goal is to loop through the array and have it create the following code and be able to keep creating lists as the data grows. I am new to php and not sure how to accomplish this.
<ul>
<li>$100,000 Cash Flow 2013</li>
<ul>
<li>Sell Iron Oak</li>
<ul>
<li>ask her if she would like to buy</li>
</ul>
<ul>
<li>Sell Car</li>
</ul>etc...
Any help will be greatly appreciated! Thank you in advance!
You need a recursive function for that, not a loop. This way it will handle any depth of your source array.
function make_list($arr)
{
$return = '<ul>';
foreach ($arr as $item)
{
$return .= '<li>' . (is_array($item) ? make_list($item) : $item) . '</li>';
}
$return .= '</ul>';
return $return;
}
echo make_list($source_array);
Seems like a simple enough recursion to me:
function arrayToList($in) {
echo "<ul>";
foreach($in as $v) {
if( is_array($v)) arrayToList($v);
else echo '<li>' . $v . '</li>';
}
echo "</ul>";
}
It looks like you have some duplicate values up there. Are you using mysql_fetch_array? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.

How to update a multi-array value?

I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the right approach.
Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).
array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" }
["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" }
["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" }
["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" }
["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" }
["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } }
Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.
Also, if the data is expected to remain uniform, you could do this:
foreach( $my_array as $index => $row ){
$my_array[$index][1] += 3;
}
cheers!
foreach ($arr as $k=>$row) {
$arr[$k][1] = floatval($row[1]) + 3;
}
foreach ($array as &$subarray) {
foreach ($subarray as $key=>&$value) {
// do whatever you want with $value
// ...
$value = 'something else'; // example
}
}
Try this:
<?php
foreach($first_array as $first_dem_key)
$first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;
?>

Categories