PHP Display an array in table format - php

I have an array like below, I need to display that array into table. I have tried the function using PHP but it getting rows and cells value, I need three type of values:
Rows name
Columns name
name for the corresponding row and column
Note : I have convert the below array1 into array 2
Array 1 :
Array
(
[0] => Array ([id] => 1[rows] => R1[columns] => c1[name] => 1)
[1] => Array([id] => 2[rows] => R1[columns] => c2[name] => 2)
[2] => Array([id] => 3[rows] => R1[columns] => c3[name] => 3)
[3] => Array([id] => 4[rows] => R2[columns] => c1 [name] => 1)
[4] => Array([id] => 5[rows] => R2[columns] => c2[name] => 2)
[5] => Array([id] => 6[rows] => R2[columns] => c3[name] => 3)
)
Array 2 :
Array
(
[0] => Array([0] => R1[1] => c1[2] => 1)
[1] => Array([0] => R1[1] => c2[2] => 2)
[2] => Array([0] => R1[1] => c3[2] => 3)
[3] => Array([0] => R2[1] => c1[2] => 1)
[4] => Array([0] => R2[1] => c2[2] => 2)
[5] => Array([0] => R2[1] => c3[2] => 3)
)
Table :
id | row | column | value
--------------------------
1 | r1 | c1 | 1
2 | r1 | c2 | 2
3 | r1 | c3 | 3
4 | r2 | c1 | 1
5 | r2 | c2 | 2
6 | r2 | c3 | 3
Function : This function convert the array2 into table
function convetTable($array) {
$rows = array();
$rows[0] = array();
foreach ($array as $column) {
if (!in_array($column[1],$rows[0])) {
$rows[0][] = $column[1];
}
}
$count = count($rows[0]);
foreach ($array as $row) {
$rowTtl = $row[0];
$rowQty = $row[1];
$rowVal = $row[2];
if (!isset($rows[$rowTtl])) $rows[$rowTtl] = array_pad(array(),$count,0);
$rows[$rowTtl][array_search($rowQty,$rows[0])] = $rowVal;
}
return $rows;
}
$table = convetTable($array2);
HTML :
{foreach from=$table item=key key=foo}
<tr class="prototype" id="first_row">
<td>Remove Row
<td><input type="text" name="rows[]" value="{$foo}" class="number" /></td>
{foreach from=$key item=cell}
<td align="center"><input type="text" name="cols[]" value="{$cell}" class="id number" /></td>
{/foreach}
</tr>
{/foreach}
Expected OutPut
0 C1 C2 C3
R1 1 2 3
R2 1 2 3
PS : here c1,c2,c3,1,2,3 are $cell value.
What I try to display $row,$col,$name, but here I'm getting $row and $cell only.
I need another value name for the corresponding row and column.

try this..
$count = count($array); //this will give you the count of elements of your array...
echo "<table border="1"><tr><th>ID</th><th>ROWS</th><th>COLUMNS</th><th>NAMES</th></tr>";
for($i=1;$i<=$count;$i++) //loop through the array..
{
echo "<tr><td>$i</td><td>".$array[$i][0]."</td><td>".$array[$i][1]."</td><td>".$array[$i][2]."</td></tr>";
}
echo "</table>";
Please note this code is to show you how to simplify your massiave code... may be you will need to edit this code to get the desired output...

Related

Determining which objects are or are not linked to the main root object

I am trying to navigate through a bunch of objects with links to other objects. I want to start with the lowest id number (the root object) and navigate through each of the objects based on connected links. Some of the object links will loop back to previous objects, so I want to make sure I look at each one only once otherwise I will get stuck in an infinite loop. I also want to be able to tell which objects cannot be accessed by navigating through the links beginning at the first link.
The tables in my database look like this:
Object Table:
+----+---------+
| id | title |
+----+---------+
| 1 | Apple |
| 3 | Carrot |
| 4 | Dill |
| 5 | Egg |
| 6 | Fred |
| 7 | Goat |
| 8 | Harry |
| 9 | Igloo |
| 10 | Jason |
| 11 | Klaus |
| 12 | Banana |
| 15 | Oyster1 |
| 16 | Oyster2 |
+----+---------+
Object_Links Table:
+----+---------+--------------+
| id | obj_id | obj_link_id |
+----+---------+--------------+
| 1 | 1 | 12 |
| 2 | 1 | 5 |
| 3 | 3 | 1 |
| 4 | 3 | 12 |
| 5 | 3 | 3 |
| 6 | 4 | 1 |
| 7 | 4 | 5 |
| 8 | 5 | 6 |
| 9 | 6 | 7 |
| 10 | 7 | 7 |
| 11 | 7 | 8 |
| 12 | 9 | 12 |
| 13 | 9 | 5 |
| 14 | 10 | 1 |
| 15 | 10 | 5 |
| 16 | 10 | 8 |
| 17 | 11 | 1 |
| 18 | 11 | 5 |
| 19 | 11 | 10 |
| 20 | 12 | 3 |
| 21 | 15 | 16 |
| 22 | 16 | 15 |
+----+---------+--------------+
So, from the table you can see that object 1 has links to both objects 12 and 5.
My SQL query looks like this:
select object.id, title, obj_link_id
from object
left join object_links ON object.id = object_links.object_id
order by object.id
which gives the table:
+----+---------+--------------+
| id | title | obj_link_id |
+----+---------+--------------+
| 1 | Apple | 12 |
| 1 | Apple | 5 |
| 3 | Carrot | 1 |
| 3 | Carrot | 12 |
| 3 | Carrot | 3 |
| 4 | Dill | 1 |
| 4 | Dill | 5 |
| 5 | Egg | 6 |
| 6 | Fred | 7 |
| 7 | Goat | 7 |
| 7 | Goat | 8 |
| 8 | Harry | NULL |
| 9 | Igloo | 12 |
| 9 | Igloo | 5 |
| 10 | Jason | 1 |
| 10 | Jason | 5 |
| 10 | Jason | 8 |
| 11 | Klaus | 1 |
| 11 | Klaus | 5 |
| 11 | Klaus | 10 |
| 12 | Banana | 3 |
| 15 | Oyster1 | 16 |
| 16 | Oyster2 | 15 |
+----+---------+--------------+
In PHP I am using:
$objects = $stmt->fetchAll(PDO::FETCH_CLASS);
I wasn't sure whether there was a better way to fetch these for my purposes so am open to suggestions.
A print_r($objects) yields:
Array
(
[0] => stdClass Object
(
[id] => 1
[title] => Apple
[obj_link_id] => 12
)
[1] => stdClass Object
(
[id] => 1
[title] => Apple
[obj_link_id] => 5
)
[2] => stdClass Object
(
[id] => 3
[title] => Carrot
[obj_link_id] => 1
)
[3] => stdClass Object
(
[id] => 3
[title] => Carrot
[obj_link_id] => 12
)
[4] => stdClass Object
(
[id] => 3
[title] => Carrot
[obj_link_id] => 3
)
[5] => stdClass Object
(
[id] => 4
[title] => Dill
[obj_link_id] => 1
)
[6] => stdClass Object
(
[id] => 4
[title] => Dill
[obj_link_id] => 5
)
[7] => stdClass Object
(
[id] => 5
[title] => Egg
[obj_link_id] => 6
)
[8] => stdClass Object
(
[id] => 6
[title] => Fred
[obj_link_id] => 7
)
[9] => stdClass Object
(
[id] => 7
[title] => Goat
[obj_link_id] => 7
)
[10] => stdClass Object
(
[id] => 7
[title] => Goat
[obj_link_id] => 8
)
[11] => stdClass Object
(
[id] => 8
[title] => Harry
[obj_link_id] =>
)
[12] => stdClass Object
(
[id] => 9
[title] => Igloo
[obj_link_id] => 12
)
[13] => stdClass Object
(
[id] => 9
[title] => Igloo
[obj_link_id] => 5
)
[14] => stdClass Object
(
[id] => 10
[title] => Jason
[obj_link_id] => 1
)
[15] => stdClass Object
(
[id] => 10
[title] => Jason
[obj_link_id] => 5
)
[16] => stdClass Object
(
[id] => 10
[title] => Jason
[obj_link_id] => 8
)
[17] => stdClass Object
(
[id] => 11
[title] => Klaus
[obj_link_id] => 1
)
[18] => stdClass Object
(
[id] => 11
[title] => Klaus
[obj_link_id] => 5
)
[19] => stdClass Object
(
[id] => 11
[title] => Klaus
[obj_link_id] => 10
)
[20] => stdClass Object
(
[id] => 12
[title] => Banana
[obj_link_id] => 3
)
[21] => stdClass Object
(
[id] => 15
[title] => Oyster1
[obj_link_id] => 16
)
[22] => stdClass Object
(
[id] => 16
[title] => Oyster2
[obj_link_id] => 15
)
)
Please note, that the number in the brackets is just the array index, not the object id number, so don't let the index throw you off.
I am trying to find a way to determine which are the linked and which are the unlinked objects. Based on the above scenario the objects should be separated as follows:
**Linked:**
Apple
Banana
Carrot
Egg
Fred
Goat
Harry
**Not Linked:**
Dill
Igloo
Jason
Klaus
Oyster1
Oyster2
My main question:
How can I create a loop in PHP to loop through a structure like this especially when each object can have multiple links? Ultimately I would like to produce two collections of objects, one containing the linked objects and one containing the unlinked objects. A sample collection might look like this:
stdClass Object
(
[LinkedElements] => stdClass Object
(
[1] => stdClass Object
(
[id] => 1
[name] => Apple
[link] => Array
(
[0] => 14
[1] => 5
)
)
[14] => stdClass Object
(
[id] => 14
[name] => Banana
[link] => Array
(
[0] => 3
)
)
[3] => stdClass Object
(
[id] => 3
[name] => Carrot
[link] => Array
(
[0] => 1
[1] => 14
[2] => 3
)
)
[5] => stdClass Object
(
[id] => 5
[name] => Egg
[link] => Array
(
[0] => 6
)
)
[6] => stdClass Object
(
[id] => 6
[name] => Fred
[link] => Array
(
[0] => 7
)
)
[7] => stdClass Object
(
[id] => 7
[name] => Goat
[link] => Array
(
[0] => 7
[1] => 8
)
)
[8] => stdClass Object
(
[id] => 8
[name] => Harry
)
)
[UnLinkedElements] => stdClass Object
(
[4] => stdClass Object
(
[id] => 4
[name] => Dill
[link] => Array
(
[0] => 1
[1] => 5
)
)
[9] => stdClass Object
(
[id] => 9
[name] => Igloo
[link] => Array
(
[0] => 14
[1] => 5
)
)
[10] => stdClass Object
(
[id] => 10
[name] => Jason
[link] => Array
(
[0] => 1
[1] => 5
[2] => 8
)
)
[11] => stdClass Object
(
[id] => 11
[name] => Klaus
[link] => Array
(
[0] => 1
[1] => 5
[2] => 10
)
)
[15] => stdClass Object
(
[id] => 15
[name] => Oyster1
[link] => Array
(
[0] => 16
)
)
[16] => stdClass Object
(
[id] => 16
[name] => Oyster2
[link] => Array
(
[0] => 15
)
)
)
)
Please note:
Navigation is done from object to link, not the other way around.
It is okay to have an object point to itself (as object 7 does).
The above sample structure (underneath my main question) is a suggestion only and I am open to other suggestions.
Disclaimer: This question is based on another question I previously asked.
In my original question I manually created the test objects, but I was not able to pull them out of my database in this fashion.
It's easier (IMHO) to deal with the data as two separate arrays. A set of objects and their links. Also, as the first part I convert the object to have the ID as the key, this allows me to use it directly rather than having to search for the ID each time.
Also to make the solution a lot simpler, I've created a flag in the object array as I visit it, so that when I try and reference it again, I can check if it's already been visited.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$objects =[[1,'apple'],
[3, 'Carrot'],
[4, 'Dill'],
[5, 'Egg '],
[6, 'Fred'],
[7, 'Goat'],
[8, 'Harry'],
[9, 'Igloo'],
[10, 'Jason'],
[11, 'Klaus'],
[12, 'Banana'],
[15, 'Oyster1'],
[16, 'Oyster2' ]];
$links =[[1,12],
[1,5],
[3,1],
[3,12],
[3,3],
[4,1],
[4,5],
[5,6],
[6,7],
[7,7],
[7,8],
[8,null],
[9,12],
[9,5],
[10,1],
[10,5],
[10,8],
[11,1],
[11,5],
[11,10],
[12,3],
[15,16],
[16,15 ]];
function buildTree ( $id, &$objects, $links ) {
foreach ( $links as $testNode ) {
if ( $testNode[0] == $id &&
$testNode[1] != $id &&
$testNode[1] != null &&
!isset($objects[$testNode[1]]['visited']) ) {
$objects[$testNode[1]]['visited'] = true;
buildTree ( $testNode[1], $objects, $links);
}
}
}
// Convert array to have the ID as key
$objects = array_combine(array_column($objects, 0), $objects);
// Fetch ID of first item
reset($objects);
$startID = key($objects);
// Mark as visited
$objects[$startID]['visited'] = true;
// Process
buildTree ( $startID, $objects, $links);
$linked = [];
$notLinked = [];
foreach ( $objects as $object) {
if ( isset($object['visited']) ) {
$linked[] = $object[1];
}
else {
$notLinked[] = $object[1];
}
}
echo "Linked...".PHP_EOL;
print_r($linked);
echo "Not linked...".PHP_EOL;
print_r($notLinked);
As you can see, the core is the recursive buildTree function. This uses &$objects as this means that all calls to the function will use the same array. As I want to build up all the uses of the items, this is important.
The condition in buildTree, checks to see if it's the node we want, it's not referring to the same node (waste of time looking any more), not null (not sure why you link to null, but again not worth looking any further) and that the node hasn't already been visited. If these conditions are OK, it marks the next node as visited and goes down into the next level.
The output is...
Linked...
Array
(
[0] => apple
[1] => Carrot
[2] => Egg
[3] => Fred
[4] => Goat
[5] => Harry
[6] => Banana
)
Not linked...
Array
(
[0] => Dill
[1] => Igloo
[2] => Jason
[3] => Klaus
[4] => Oyster1
[5] => Oyster2
)
This is a graph traversal problem. Starting from a node (root) you want to traverse the graph keeping track of each node visited along the way. Once the traversal is over, visited ones are connected. Breadth-first search can be done in this way:
//To form a graph fetch all objects from the database (sorted by id) and
//index them in a hash map
$objects = $stmt->fetchAll(PDO::FETCH_OBJ);
$nodes = [];
foreach ($objects as $object) {
$nodes[$object->id] = new Node($object);
}
//fetch all connections from the database and link the objects
$links = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($links as $link) {
$nodes[$link->obj_id]->addLink($nodes[$link->obj_link_id]);
}
//let's assume root is the first node (sorted by id),
//traverse the graph starting from root
$root = reset($nodes);
$root->traverse();
//now if a node can be reached by the root it is marked as visited
$linked = [];
$notLinked = [];
foreach ($nodes as $node) {
if ($node->isVisited()) {
$linked[] = $node;
} else {
$notLinked[] = $node;
}
}
And the node class:
class Node
{
/**
* List of neighbor nodes.
*
* #var Node[]
*/
private $links = [];
/**
* id, title info
*
* #var array
*/
private $data = [];
/**
* To track visited nodes.
*
* #var bool
*/
private $visited = false;
/**
* Node constructor.
* #param array $data
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Add a link to this node.
*
* #param Node $node
* #return void
*/
public function addLink(Node $node)
{
$this->links[] = $node;
}
/**
* Traverse the graph in a Breadth-First-Search fashion marking
* every visited node.
* #return void
*/
public function traverse()
{
//initialize queue
$q = new SplQueue();
//add root to queue and mark as visited
$q->enqueue($this);
$this->visited = true;
while (!$q->isEmpty()) {
/** #var Node $cur */
$cur = $q->dequeue();
foreach ($cur->links as $link) {
//if link not visited already add it to queue and mark visited
if (!$link->visited) {
$link->visited = true;
$q->enqueue($link);
}
}
}
}
/**
* Checks if node has been visited.
*
* #return bool
*/
public function isVisited()
{
return $this->visited;
}
}
Let's say the "root" is obj_id 1.
Here's a somewhat brute force algorithm, but it takes advantage of SQL's liking of 'set' operations.
Insert into table1 the root (1)
Loop
Create table2 with all nodes linked to any node in table1
Exit if number of rows in table2 = num rows in table1
table1 := table2
Closer to SQL:
# Initialize:
CREATE TABLE table1 (
obj_id ...
PRIMARY KEY(obj_id)
)
SELECT 1; # assuming root is 1
start of loop:
CREATE TABLE table2 (
obj_id ...
PRIMARY KEY(obj_id)
)
SELECT DISTINCT obj_link_id
FROM table1
JOIN object_links USING(obj_id);
SELECT #fini := ( SELECT COUNT(*) FROM table1 ) =
( SELECT COUNT(*) FROM table2 ) # will give true/false
DROP TABLE table1;
RENAME TABLE table2 TO table1;
loop if #fini=0
The output is all the 'connected' ids. If you want the unconnected ones:
SELECT obj_id
FROM object_links
LEFT JOIN table1 USING(obj_id)
WHERE table1.obj_id IS NULL; # that is, missing from table1
Here is a pretty short way to get all linked IDs:
$pdo = new PDO('mysql:host=localhost;dbname=test_obj_link', 'testread', 'testread');
$links = $pdo
->query('select obj_id, obj_link_id from object_links')
->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
function getLinks($objId, $links, $indirectNodes = []) {
$directNodes = isset($links[$objId]) ? $links[$objId] : [];
foreach($directNodes as $linkedNode) {
if (!in_array($linkedNode, $indirectNodes)) {
$indirectNodes[] = $linkedNode;
$indirectNodes = array_unique(array_merge(
$indirectNodes,
getLinks($linkedNode, $links, $indirectNodes)
));
}
}
return $indirectNodes;
}
$linkedObjectIds = getLinks(1, $links);
fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN) will return a structured array with links per object indexed by objectIDs which looks like:
$links = [
1 => ['5', '12'],
3 => ['1', '3', '12'],
4 => ['1', '5'],
5 => ['6'],
6 => ['7'],
7 => ['7', '8'],
9 => ['5', '12'],
10 => ['1', '5', '8'],
11 => ['1', '5', '10'],
12 => ['3'],
15 => ['16'],
16 => ['15'],
];
The getLinksfunction will "walk" the $links array recursively and merge all child arrays that are found on the way. Since PHP doesn't seem to have an array_union function - array_unique(array_merge(..)) is used instead.
The result:
$linkedObjectIds = array (
0 => '5',
1 => '6',
2 => '7',
3 => '8',
4 => '12',
10 => '3',
11 => '1',
)
Note that the indexes have no meaning here.
To get the corresponding objects you can do the following:
$objects = $pdo
->query('select id, title from object')
->fetchAll(PDO::FETCH_KEY_PAIR);
$linkedObjects = array_intersect_key($objects, array_flip($linkedObjectIds));
$notLinkedObjects = array_diff_key($objects, $linkedObjects);
The variables will contain:
$objects = array (
1 => 'Apple',
3 => 'Carrot',
4 => 'Dill',
5 => 'Egg',
6 => 'Fred',
7 => 'Goat',
8 => 'Harry',
9 => 'Igloo',
10 => 'Jason',
11 => 'Klaus',
12 => 'Banana',
15 => 'Oyster1',
16 => 'Oyster2',
);
$linkedObjects = array (
1 => 'Apple',
3 => 'Carrot',
5 => 'Egg',
6 => 'Fred',
7 => 'Goat',
8 => 'Harry',
12 => 'Banana',
);
$notLinkedObjects = array (
4 => 'Dill',
9 => 'Igloo',
10 => 'Jason',
11 => 'Klaus',
15 => 'Oyster1',
16 => 'Oyster2',
);
Demo: http://rextester.com/ZQQGE35352
Note that in_array() and array_unique() are probably slow, since they have to search in values, which are not sorted. This might lead to performance issues on some datasets. Assuming that PHP can search the keys faster, we could use array_key_exists() instead of in_array() and the array operator + (union by keys) instead of array_unique(array_merge()). And the code will even be a bit shorter:
function getLinks($objId, $links, $indirectNodes = []) {
$directNodes = isset($links[$objId]) ? $links[$objId] : [];
foreach($directNodes as $linkedNode) {
if (!array_key_exists($linkedNode, $indirectNodes)) {
$indirectNodes[$linkedNode] = 0;
$indirectNodes = $indirectNodes + getLinks($linkedNode, $links, $indirectNodes);
}
}
return $indirectNodes;
}
However - since the function now returns the needed result as keys, we would need to use array_keys() to extract them:
$linkedObjectIds = array_keys(getLinks(1, $links));
Demo: http://rextester.com/GHO7179

How to execute that in 1 query?

I have 2 tables customer and orders:
customers:
| custID | Name | Age |
|--------|-------|-----|
| 1 | Peter | 23 |
| 2 | Julie | 34 |
| 3 | Tom | 45 |
orders:
| custID | product | color |
|--------|---------|-------|
| 1 | shirt | blue |
| 1 | jacket | black |
| 2 | jacket | green |
| 3 | hat | grey |
| 3 | shirt | white |
I now want to get all customers and their orders, ordered as a list. So something like that:
Array
(
[0] => Array
(
[ID] => 1
[name] => Peter
[age] => 23
[orders] => Array
(
[0] => Array
(
[product] => shirt
[color] => blue
)
[1] => Array
(
[product] => jacket
[color] => black
)
)
)
[1] => Array
(
[ID] => 2
[name] => Julie
[age] => 34
[orders] => Array
(
[0] => Array
(
[product] => jacket
[color] => green
)
)
)
[2] => Array
(
[ID] => 3
[name] => Tom
[age] => 45
[orders] => Array
(
[0] => Array
(
[product] => hat
[color] => grey
)
[1] => Array
(
[product] => shirt
[color] => white
)
)
)
)
When I do:
SELECT name, age, product, color
FROM `customers`, `orders`
where `customers`.`id` = `orders`.id
group by name
I get:
| name | age | product | color |
|-------|-----|---------|-------|
| Peter | 23 | jacket | green |
| Julie | 34 | shirt | blue |
| Tom | 45 | hat | grey |
Is this even possible with only one query?
You could simply make the query below:
SELECT *
FROM customers
JOIN orders
USING custID
GROUP BY Name
ORDER BY custID ASC;
A couple of steps here...
First, you should run the following query:
SELECT
`customers`.`id`,
`customers`.`name`,
`customers`.`age`,
`orders`.`product`,
`orders`.`color`
FROM `customers`, `orders`
where `customers`.`id` = `orders`.`id`
order by `customers`.`id`
Which should give you de-normalized tabular data that looks something like this:
$array = array(
array("id" => 1, "name" => "Peter", "age" => 23, "product" => "shirt", "color" => "blue"),
array("id" => 1, "name" => "Peter", "age" => 23, "product" => "jacket", "color" => "black"),
array("id" => 2, "name" => "Julie", "age" => 34, "product" => "jacket", "color" => "green"),
array("id" => 3, "name" => "Tom", "age" => 45, "product" => "hat", "color" => "grey"),
array("id" => 3, "name" => "Tom", "age" => 45, "product" => "shirt", "color" => "white")
);
You can then transform the that data into your desired format as follows:
$transformed = array();
$i = 0;
while ($i < count($array)) {
$id = $array[$i]["id"];
$name = $array[$i]["name"];
$age = $array[$i]["age"];
$products = array();
while ($i < count($array) && $id == $array[$i]["id"]) {
array_push($products, array("product" => $array[$i]["product"], "color" => $array[$i]["color"]));
$i++;
}
array_push($transformed, array("id" => $id, "name" => $name, "age" => $age, "products" => $products));
}
http://sandbox.onlinephpfunctions.com/code/6fe856e1f71f699e84215b6f66d25589f71e255e
i think you should user INNER JOIN:
SELECT * FROM customers AS c INNER JOIN orders AS o ON c.custID = o.custID GROUP BY c.custID ORDER BY c.custID ASC;
There is no point in trying to achieve the desired outcome with single query. With the first query get the list of customers. Then perform a second query, which will load all the orders for the customers from the first query. And in a loop match orders to respective customers.
EDIT: something like this
$result = [];
$customers = $pdo->query("SELECT * FROM `customers`")->fetchAll();
foreach ($customers as $c) {
$result[$c['id']] = $c;
}
$orders = $pdo->query("SELECT * FROM `orders` WHERE `custID` IN (".implode(', ', array_keys($result).")");
foreach ($orders as $o) {
if (!isset($result[$o['custId']]['orders']))
$result[$o['custId']]['orders'] = [];
$result[$o['custId']]['orders'][] = $o;
}
Your sql SELECT name, age, product, color FROMcustomers,orderswherecustomers.id=orders.id group by name is fine, just add the customer id and order id also in the sql. Then, in PHP, as you iterate the result set, populate the customer info first (id, name, age) with customer id as the key and name, age as value as an array. Likewise, populate the order for that customer in the key 'orders' with the order id as key and value as an array (product, color).
Once you have the array populated, iterate over that array and keep putting things into a new array since the output you want is an array with sequential keys (0, 1, 2 etc) instead of customer id.
$initialList = array();
while($row = $result->fetch_assoc()) {
if(!array_key_exists($row['customer_id'], $initialList)) {
$initialList[$row['customer_id']] = array(
'name' => $row['name'],
'age' => $row['age'],
'orders' => array()
);
}
$initialList[$row['customer_id']]['orders'][] = array(
'product' => $row['product'],
'color' => $row['color']
);
}
$finalList = array();
foreach($initialList as $customerId => $customer) {
$customer['ID'] = $customerId;
$finalList[] = $customer;
}
//to print and check the array
print_r($finalList);
try this:
SELECT c.custID,c.name, c.age, group_concat(CONCAT_WS(':',o.product,o.color)SEPARATOR ',') as productos
FROM customers AS c
INNER JOIN orders AS o ON c.custID = o.custID
GROUP BY c.custID;
You just have to parse the products.
$array=array();
while($r = $res->fetch_assoc()) {
$id=$row['custID'];
$name=$row['name'];
$age=$row['age'];
$productos=$row['productos'];
$productsSeparats = explode(',',$productos);
$orders=array();
foreach ($productsSeparats as $value) {
$ar=explode(':',$value);
array_push($orders, array("product" => $ar[0], "color" => $ar[1]));
}
array_push($array, array("id" => $id, "name" => $name, "age" => $age, "orders" => $orders));
}

PHP: Store dynamically generated text field values in database

I have one array contains the result set from dynamically generated text box values.
In the below example I created three dynamically generated rows and each row contains 6 text field. For differentiate each row name i added the row id as the last word of name. Example ClaimExecutionCountry1 means ClaimExecutionCountry as the name and 1 is the row id.
Array
(
[0] => ClaimExecutionCountry1=10
[1] => activitystartdate1=05-27-2016
[2] => activityenddate1=06-24-2016
[3] => CLCode1=CLC1
[4] => SCSCode1=SCS1
[5] => fileName1=calc2.png
[6] => ClaimExecutionCountry2=53
[7] => activitystartdate2=05-27-2016
[8] => activityenddate2=05-28-2016
[9] => CLCode2=
[10] => SCSCode2=
[11] => fileName2=gh.png
[12] => ClaimExecutionCountry3=82
[13] => activitystartdate3=05-26-2016
[14] => activityenddate3=07-28-2016
[15] => CLCode3=
[16] => SCSCode3=SCS5
[17] => fileName3=preview1.png
)
I am facing one issue for storing these values in Database. In my database structure is below
Id | ClaimExecutionCountry | activitystartdate | activityenddate | CLCode | SCSCode | fileName
I need to store after = symbol values in this table.
after insert the table, the result would be
Id | ClaimExecutionCountry | activitystartdate | activityenddate | CLCode | SCSCode | fileName
------------------------------------------------------------------------------------------------------------
1 | 10 | 05-27-2016 | 06-24-2016 | CLC1 | SCS1 | calc2.png
2 | 53 | 05-27-2016 | 05-28-2016 | null | null | gh.png
3 | 82 | 05-26-2016 | 07-28-2016 | null | SCS5 | preview1.png
So Anyone please help me to store the array values in database using above format. I think you understood my problem. I am using PHP,codignator and MySql as database. Thanks in advance
Please try code below:
$_array=Array(
[0] => ClaimExecutionCountry1=10
[1] => activitystartdate1=05-27-2016
[2] => activityenddate1=06-24-2016
[3] => CLCode1=CLC1
[4] => SCSCode1=SCS1
[5] => fileName1=calc2.png
[6] => ClaimExecutionCountry2=53
[7] => activitystartdate2=05-27-2016
[8] => activityenddate2=05-28-2016
[9] => CLCode2=
[10] => SCSCode2=
[11] => fileName2=gh.png
[12] => ClaimExecutionCountry3=82
[13] => activitystartdate3=05-26-2016
[14] => activityenddate3=07-28-2016
[15] => CLCode3=
[16] => SCSCode3=SCS5
[17] => fileName3=preview1.png
)
foreach($_array as $val){
$a = explode("=",$val);
$field = $a[0];
$ans=$a[1];
$matches = array();
if (preg_match('#(\d+)$#', $field, $matches)) {
$rowNum=$matches[1];
}
$fieldName = str_replace($rowNum,"",$field);
/*Now you have number of row , $fieldName , $rowNum and $ans so we can execute SQl statement inside forEach*/
}
Hope it will help you.
$a = Array
(
[0] => ClaimExecutionCountry1=10
[1] => activitystartdate1=05-27-2016
[2] => activityenddate1=06-24-2016
[3] => CLCode1=CLC1
[4] => SCSCode1=SCS1
[5] => fileName1=calc2.png
[6] => ClaimExecutionCountry2=53
[7] => activitystartdate2=05-27-2016
[8] => activityenddate2=05-28-2016
[9] => CLCode2=
[10] => SCSCode2=
[11] => fileName2=gh.png
[12] => ClaimExecutionCountry3=82
[13] => activitystartdate3=05-26-2016
[14] => activityenddate3=07-28-2016
[15] => CLCode3=
[16] => SCSCode3=SCS5
[17] => fileName3=preview1.png
)
Take the count of array------
$cnt = count($a);
<!--now loop it and explode it to get the values after = -->
for($i=0;$i<=$cnt;$i++){
$b = explode("=",$a[i]);
<!--exploded value will give $b[0] = hhjhj and $b[1] = 10 ok -->
$c[] = $b[1];
}
<!-- In $c array all the values came after =.....now -->
$k=0;
$l=6;
$h=0;
for($j=$k;$j<=$l;$j++){
if($j == $l){
$j = $k;
$l = $l + 5;
$h++;
}
<!-- So from this here we got no of set of rows to be inserted in table --it will give result [3] from array $c(mixed values of no of rows) -->
}
<!-- now going to split into rows and insert-->
for($i=1;$i<=3;$i++){
$e=6;
for($j=0;$j<=$e;$j++){
if($j==$e){
$j=$e+1;
$e = $e+6;
break;
}else{
$row[$i] = $c[$j];
}
}
}
<!-- now we got --- -->
$row[1] = {0,date,date,ccsc,sslc,image};
$row[2] = {0,date,date,ccsc,sslc,image};
$row[3] = {0,date,date,ccsc,sslc,image};

PHP fill the missing values with empty values in an array

I have the array like
array(
[0] => array(
[a] => r1,
[b] => c1,
[c] => d1,
),
[1] => array(
[a] => r1,
[b] => c1,
[c] => d2,
),
[2] => array(
[a] => r1,
[b] => c1,
[c] => d3,
),
[3] => array(
[a] => r1,
[b] => c2,
[c] => d1,
),
[4] => array(
[a] => r1,
[b] => c2,
[c] => d3,
),
[5] => array(
[a] => r1,
[b] => c3,
[c] => d1,
)
)
Currently I am getting the output like
-------------------------------------
| C1,D1 | C1,D2 | C1,D3 |
-------------------------------------
| C2,D2 | C3,D1 | - |
-------------------------------------
| - | - | - |
-------------------------------------
But I need the output must be displayed by 3x3 matrix Like
-------------------------------------
| C1,D1 | C1,D2 | C1,D3 |
-------------------------------------
| - | C2,D2 | - |
-------------------------------------
| C3,D1 | - | - |
-------------------------------------
Please help me to fill the missing values with empty values
My code :
for($i=1; $i<=3; $i++){
for($j=1; $j<=3; $j++){
for($r=0; $r<9; $r++){
if(isset($rows[$r]) && $rows[$r]['b'] == 'C'.$i && $rows[$r]['c'] == 'D'.$j) {
//Store data to array
$data[] = array(
'a' => $rows[$r]['a'],
'b' => $rows[$r]['b'],
'c' => $rows[$r]['c']
);
}
}
}
}
Option => Fill the array with empty values then fill in the values you got.
Option => Remember which index positions you fill and then fill the rest by excluding the ones u filled.
Number 1 is easier.
Number 2 has better performance.
You can use array_fill
or do a loop through the array:
for( $i = 0 ; $i < MAX ; $i++ )
arr[i] = ""; // fill with whatever value you like

How to count the number of same values in php or mysql

p1 p2 p3 p4 p5 p6 p7 p8
---------------------------------------------------------------------------------------
1414 1414 1417 1417 1422,1421 1422,1421 1422,1421 1422,1421
The above table has 8 columns in which the adjacent columns having same values. How to count the number of columns based on the column values in php or in mysql..
For Eg :
for 1414---values are p1,p2 and count is 2
for 1422,1421--- values are p5,p6,p7,p8 and count is 4.
Can any one help me in this..
Array
(
[0] => Array
(
[period] => p1
[subject] => 1434
[nop] => 1
)
<b>
**[1] => Array
(
[period] => p2
[subject] => 1440,1439
[nop] => 1
)
[2] => Array
(
[period] => p2,p3
[subject] => 1440,1439
[nop] => 2
)**
</b>
[3] => Array
(
[period] => p2,p3,p4
[subject] => 1440,1439
[nop] => 3
)
[4] => Array
(
[period] => p5
[subject] => 1442
[nop] => 1
)
[5] => Array
(
[period] => p6
[subject] => 1442
[nop] => 1
)
[6] => Array
(
[period] => p7
[subject] => 1442
[nop] => 1
)
)
I have got the above array.. how to remove the above highlighted values in the above array from it.
suppose your $row has reesult of table
$your_val = '1414'; // for eg 1414
$result_col = ""; // will contain you columns
$result_count = 0; // will contain your count
// $row has the each column value when you fetch from database eg $row['p1'] = 1414
foreach($row as $key=>$val)
{
if($val==$your_val)
{
$result_count += 1;
if($result_text=="")
{
$result_col = $key;
}
else
{
$result_col = $result_col.",".$key;
}
}
}
echo "values are ".$result_col." and count is ".$result_count; // output
You can do it with MySQL:
SELECT
IF(p1='1414',1,0) + IF(p2='1414',1,0)+ IF(p3='1414',1,0) + IF(p4='1414',1,0) + IF(p5='1414',1,0) + IF(p6='1414',1,0) + IF(p7='1414',1,0) + IF(p8='1414',1,0) AS cnt
FROM your_table;
If you are using PHP to access the databasem, you can replace the '1414' with a variable to count the occurences of the variable's value.

Categories