i have generated a json according to my sql query out put here is my json output, i have listed few of my json code
"42":"",
"field_id_25":"",
"43":null,
"field_ft_25":null,
"44":"",
"field_id_26":"",
"45":null,
"field_ft_26":null,
"46":"",
"field_id_27":"",
"47":null,
"field_ft_27":null,
i have to change json key field_ft_$$ according to my database table values..
|---------------------|------------------|
| field id | field name |
|---------------------|------------------|
| field_id_27 | meta_description |
|---------------------|------------------|
ive coded in php then after i dont know how to finish..
<?php
$con=mysqli_connect("localhost","root","","penn");
if (!$con) {
echo "Failed";
}
// Retrive Data From WebLog Title
$sql="SELECT * FROM `exp_weblog_titles` LEFT JOIN `exp_weblog_data` ON `exp_weblog_data`.`entry_id` = `exp_weblog_titles`.`entry_id` WHERE exp_weblog_titles.weblog_id='13' LIMIT 2 ";
$query=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($query))
{
$data[] = $row;
}
// Convert The Weblog title data to json
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;
// Retrive web_log_field_List as a array from database
$sql1="SELECT field_id,field_name FROM exp_weblog_fields";
$query1=mysqli_query($con,$sql1);
while ($row1=mysqli_fetch_array($query1)) {
$web_log_field[$row1['field_id']] = $row1['field_name'];
}
// echo $web_log_field[21];
?>
example - i need to change "field_ft_27":null to "meta_description": null and others according to my database values
Use a regular expression to extract the appropriate parts of field_ft_XX and get the corresponding field_id_XX element of $web_log_field. Then you can delete the old key and add the replacement key.
foreach ($data as &$row) {
foreach ($row as $key => $value) {
if (preg_match('/^field_ft_(\d+)$/', $key)) {
$idkey = "field_id_$key[1]";
if (isset($web_log_field[$idkey])) {
$row[$web_log_field[$idkey]] = $value;
unset($row[$key]);
}
}
}
}
Related
I currently have the following:
$query='select concat("[",key,"=>",value,"]")
from table';
if(isset($query))$r=$mysql->query($query);
if(isset($r)){
for($i=1;$i<=$r->num_rows;$i++){
$r->data_seek($i-1);
$a[$i-1]=$r->fetch_array(MYSQLI_ASSOC);
$a[$i-1]=parse_array($a[$i-1]);
}
}
$mysql->close;
function parse_array($parent){
foreach($parent as$k=>$val){
if(strpos($val,']')){
$array=explode(',',substr($val,1,-1));
foreach($array as$val){
$keypair=explode("=>",$val);
$newarray[$keypair[0]]=$keypair[1];
}
$parent[$k]=parse_array($newarray);
}
}
}
There has to be a more elegant way of doing this - perhaps built into MySQL? I'm trying to minimize the time this spends running PHP - I would like it to arrive to PHP already in array form, but MySQL kicks Subquery returns more than one result if I attempt a subquery.
Edit: Here's table:
+----------+----------+
| value | key |
+----------+----------+
| img.jpg | src |
+----------+----------+
Output should be:
[
'src'=>'img.jpg'
]
Just move all of the manipulation over to php. Fetch the query with numeric indexes. Make the assumption that the every even index is a key and every odd index is a value (or vice versa).
$query = 'select key1, value1, key2, value2
from table';
if(isset($query))
$result = $mysql->query($query);
if(isset($result)) {
$newResult = []; // if your version of php doesn't support this syntax to create a new array use `$newResult = array();`
while($row=$result->fetch_array(MYSQLI_NUMERIC)) {
$newResult[] = build_assoc_array($row);
}
}
$mysql->close;
function build_assoc_array($flat_arr) {
$newArr = [];
$numCol = count($flat_arr);
for($colIndex = 0; $colIndex < $numCol; $colIndex+=2) {
$newArr[$flat_arr[$colIndex]] = $flat_arr [$colIndex+1];
}
return $newArr;
}
I'm using a "foreach" statement to fetch all images from a folder to print on webpage.
I also need to give 'links' to these images.
Links are saved in database table called 'advertisement'.
I fetched all images and displayed correctly.
but I can't make these images as links.
I also used another "foreach" statement to fetch 'link' rows from table 'advertisement' table.
but how to combine these two.
Here is an example of how you could do it:
$files = array('1.jpg','2.jpg');
$stm = $pdo->query('SELECT * FROM advertisement');
$linkInfo = $stm->fetchAll(PDO::FETCH_ASSOC);
$outputArray = array();
foreach( $linkInfo as $row )
{
if( in_array($row['file'], $files) )
{
$outputArray['file'] = $row['link'];
}
}
foreach( $outputArray as $file => $link )
{
echo "<a href='".$link."'><img src='". $file ."'></a>";
}
Not sure how your structure is, but say you have a table like this:
------------------------------
| file | link |
------------------------------
| 1.jpg | http://... |
+
+
+
This should work, with some adjustment according to your own structure.
I've create a simple table of analogs:
+----+-------+-------+
| id | sku_1 | sku_2 |
+----+-------+-------+
| 1 | a1 | abcd |
| 2 | a2 | a3 |
| 3 | a3 | a1 |
+----+-------+-------+
3 rows in set (0.00 sec)
What it mean? It mean that product with article abcd has an analog with article a1, otherwise for example product with article a3 has an analog with article a1.
How to recursively get all the products from this table by a single article?
My solutions is wrong:
// Small Class to get analogs of products
class Analogs {
public function get_analogs($sku)
{
if (!$sku) return false;
$link = mysql_connect('localhost','','');
mysql_select_db('test');
$sku = mysql_real_escape_string($sku,$link);
$query = mysql_query("SELECT * FROM analogs WHERE sku_1='".$sku."' OR sku_2='".$sku."'");
while($analogs[]=mysql_fetch_assoc($query))
continue;
return $analogs;
}
public function MixedAnalogs($sku)
{
if (!$sku) return false;
$link = mysql_connect('localhost','','');
mysql_select_db('test');
$sku = mysql_real_escape_string($sku,$link);
$query = mysql_query("select sku_1 sku from analogs where sku_2 = '$sku' UNION
select sku_2 sku from analogs where sku_1 = '$sku'");
while($analogs[]=mysql_fetch_assoc($query))
continue;
return $analogs;
}
}
$mixed_analogs = AnalogsMix('abcd',$ids=array());
echo "<pre>";
print_r($mixed_analogs);
echo "</pre>";
// Recursive function to get analogs of analog
function AnalogsMix($sku,$ids=array())
{
$class_analogs = new Analogs();
$analogs = $class_analogs->get_analogs($sku);
foreach ($analogs as $analog)
{
$cross = null;
if ($analog['sku_1']==$sku)
{
$cross->sku = $analog['sku_2'];
}
else
{
$cross->sku = $analog['sku_1'];
}
$cross->id = $analog['id'];
if (!in_array($analog['id'],$ids))
{
$ids[] = $analog['id'];
$mixed[] = AnalogsMix($cross->sku,$ids);
}
}
if (isset($mixed))
{
return $mixed;
}
else
{
return false;
}
}
SQL UNION
select sku_1 sku from analogs where sku_2 = $yourid
union
select sku_2 sku from analogs where sku_1 = $yourid
Then you will get in results only ids of analogs.
Here, I suppose you have all your pairs in an array. For example, for your example, you would call analogsOf(array(array("a1", "abcd"), array("a2", "a3"), array("a3", "a1")), "abcd").
The idea is that you build a list of analogs containing initially only the string you are looking for and, every time you find an analog, you add it to the list of analogs and reiterate. You do so until you iterated the whole array of pairs without finding anything new.
function analogsOf(array $pairs, $key) {
$res = array($key); // The result, with only the given key
$i = 0; // Index of the current item
$changed = false; // Have we added an item to $res during that iteration ?
while ($i < count($pairs)) {
$current = $pairs[$i];
foreach ($res as $item) {
if (($current[0] === $item) && (!in_array($current[1], $res)) {
$res[] = $current[1];
$i = 0; // Reiterate as $res changed
}
else if (($current[1] === $item) && (!in_array($current[0], $res)) {
$res[] = $current[0];
$i = 0; // Reiterate as $res changed
}
else {
$i++; // Nothing found here, go to next item
}
}
}
return $res;
}
Note that this code was NOT tested, so there might be a few bugs here and there, but you've got the idea. Also note that I considered you could put the whole database content in an array, but that is probably not possible for obvious reasons, so you will probably have to adapt the code above.
I found a solution for this problem but the main problem in this approach is that.
it can make a loop like abcd->a1,a1->a3,a3->a2,a2->abcd. and it make recursive function endless and php throw an error. so you have to check for that if it is a big project.
in my solution i consider it parent-> child relation. and if a child found make it parent and check again and so on until there is no result.
let abcd is parent and after first execution a1 is child and relation is abcd->a1. but in next call a1 is parent and from first row of table it give a new relation that is a1->abcd and loop is endless.
To prevent checking in same row i use ID of last row from database and it now check row where id != ID (always check other row)
this is function i write, convert it according to your class and store the value in array as you like. I use a string only.
i knew it not a good solution but i works fine.
<?php
mysql_connect('localhost','','');
mysql_select_db('test');
function getSku($sku, $id, $rel = '') {
$query = mysql_query("SELECT * FROM analogs WHERE sku_1 = '$sku' AND id != '$id'" );
if (mysql_num_rows($query)) {
$row = mysql_fetch_assoc($query);
$sku = $row['sku_2']; //PARENT SKU
$id = $row['id']; //LAST ID
$rel .= $row['sku_1']. '-->' . $row['sku_2']. "<br>";
} else {
$query = mysql_query("SELECT * FROM analogs WHERE sku_2 = '$sku' AND id != '$id'" );
if (mysql_num_rows($query)) {
$row = mysql_fetch_assoc($query);
$sku = $row['sku_1']; //PARENT SKU
$id = $row['id']; //LAST ID
$rel .=$row['sku_2']. '-->' . $row['sku_1']. '<br>';
} else {
return (string)$rel; //NOTHING FOUND
}
}
return getSku($sku,$id,$rel);
}
echo $new = getSku('abcd','-1');
I got a table as DOMDocument which looks like this:
name | user | comment
-----------------------------
Test | user1 | Line 1
Abc | user2 | Line 1
| | Line 2
Test2 | user3 | Line 1
Test3 | user3 | Line 1
| | Line 2
| | Line 3
as you can see, sometimes the comment Wraps over multiple tablerows. (Apparently when the comment is a long one)
When those wraps occur, all fields except for the comment one are empty.
How can I merge those wrapped comments together and output them?
I am currently outputting them like this:
foreach ($xml->getElementsByTagName('table')->item(1)->getElementsByTagName('tr') as $row) {
echo "<tr>";
foreach ($row->getElementsByTagName('td') as $column) {
echo "<td>" . $column->textContent . "</td>";
}
echo "</tr>";
}
}
You are outputting each row before you know what the next one contains. A different approach would be to store each row in an array, allowing you to correct the previous row if the following row meets a certain condition (eg. wrapping). You can then output the resulting array as an HTML table once processed.
Something like this (untested):
// build array
$rows = array();
$xmlRows = $xml->getElementsByTagName('table')->item(1)->getElementsByTagName('tr');
foreach ($xmlRows as $xmlRow) {
$emptyFields = 0;
$row = array();
$xmlColumns = $xmlRow->getElementsByTagName('td');
foreach ($xmlColumns as $xmlColumn) {
if (empty($xmlColumn->textContent)) { // count empty fields
$emptyFields++;
}
$row[] = $xmlColumn->textContent;
}
if ($emptyFields >= 2) { // detect if wrapping has occurred
$lastRow = array_pop($rows); // remove last row from array
$lastRow[2] .= $row[2]; // update last row with wrapped data
$row = $lastRow; // use newly merged row
}
$rows[] = $row;
}
// output array
foreach ($rows as &$row) {
$row = '<td>' . implode('</td><td>', $row) . '</td>';
}
echo '<table><tr>' . implode('</tr><tr>', $rows) . '</tr></table>';
I'm failing miserably to get my head around what I know ought to be simple, and am unsure if the solution lies in the query or in processing the result, so struggling to search for what I'm sure has been covered in another post.
I'm working with a single MySQL table, from which I need to be able to retrieve and process content that shares a common ID. Unfortunately, restructuring the database isn't an option.
Here's what a simple SELECT * WHERE contentID = '2' query returns:
|contentType|contentID|content |
--------------------------------------
|title |2 |<h1>title</h1>|
|intro |2 |<p>intro</p> |
|main |2 |<p>main</p> |
What's the correct way to retrieve the specific 'title', 'intro' or 'main' content?
Thanks in advance.
$result = mysql_query("SELECT * WHERE contentID = '2'");
$array = array();
while($rows = mysql_fetch_array($result,MYSQLI_ASSOC)){
$array[$rows['contentType']] = $rows['content'];
}
You can use the $array for each content type
Fetch all the rows into an array:
$data = array();
foreach ($rows as $r) {
$data[$r['contentType']] = $r['content'];
}
You'd have to put your content type into the where clause. The Id and type should form a natural ok and should be constrained as such. If not, time to redesign. Also, id consider putting the content type as a lookup rather than a string.
<?php
function executeQuery($query,$connectionObject)
{
queryString=$query;
recordSet=mysql_query(queryString,$connectionObject);
if(!$recordSet)
{
$errorString=mysql_error($this->connectionObject);
return array("error"=>$errorString);
}
return recordSet;
}
function getNextRecord($recordSet)
{
$resultArray =mysql_fetch_assoc($recordSet);
if(!empty($resultArray))
return($resultArray);
else
return "false";
}
$result = executeQuery("SELECT * FROM foo WHERE contentID = '2'");
$nextRecord = getNextRecord($result);
while($nextRecord!="false")
{
$nextRecord = getNextRecord($result);
//...........Process the record.....
->$nextRecord['contentType'];
->$nextRecord['contentID'];
->$nextRecord['content'];
//..................................
}