How to loop multidimensional array from mysql table with php - php

After reading muiltiple stackoverflow questions I'm still confused on why I am not able to get this to work. I am attempting to take all of the rows of a mysql table and put them into a multidimensional array. I was hoping to just find a simple example but so far I'm not fully understanding.
The examples I've seen on google and stack is mostly about parsing or making it iterate on the page. I am attempting to have the mysql rows iterate into their arrays. The example code I started working with was similiar to this:
// This will hopefully get all of the categories
case 'get_all_categories' :
$query = '
SELECT `id`,`category_name`, `category_spam`
FROM `category`
';
if (!$go = #mysql_query($query)) {
$results = Array(
'head' => Array(
'status' => '0',
'error_number' => '604',
'error_message' => 'Select Failed. '.
'Probably wrong name supplied.'
),
'body' => Array ()
);
} else {
$fetch = mysql_fetch_row($go);
$return = Array($fetch[0],$fetch[1]);
$results = Array(
'body' => Array (
'id' => $return[0],
'category_name' => $return[1]
)
);
}
break;
This obviously provides me with the result of just ONE as that is what I'm asking it to do with fetch_row.
i.e.
//outputs
{"body":{"id":"1","category_name":"Star Wars"}}
I've attempted to use mysql_fetch_assoc and then do a foreach loop?
I"ve also tried doing a mysql_fetch_all($go) and then attempt to put the rows into it.
if (!$go = #mysql_query($query)) {
$results = Array(
'head' => Array(
'status' => '0',
'error_number' => '604',
'error_message' => 'Select Failed. '.
'Probably wrong name supplied.'
),
'body' => Array ()
);
} else {
while($myrow = mysql_fetch_row($go)){
Array(
'body' => Array(
'id' => $myrow[o],
'category_name' => $myrow[1],
'category_spam' => $myrow[2]
)
}
);
}
break;
I am attempting to make an api call where the body holds all of the categories and their id's (the point I believe is then for the categories to pull and show the lists...which I'm hoping is the right away to make an api(not a question just rambling)
So: how do I make the query take all of the mysql rows and loop them into arrays for the body array. (note: I'm new to API's if my terminology is wrong to what my overall goal is which is to get an api call to show my whole mysql array then please let me know).
EDIT Just adding more info from the comments
The output is JSON encoded (sorry I should have explained that)
switch ($_GET['format']) {
case 'xml' :
#header ("content-type: text/xml charset=utf-8");
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('callback');
$xml->writeAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance');
$xml->writeAttribute('xsi:noNamespaceSchemaLocation','schema.xsd');
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $results);
$xml->endElement();
echo $xml->outputMemory(true);
break;
case 'json' :
#header ("content-type: text/json charset=utf-8");
echo json_encode($results);
break;
case 'php' :
header ("content-type: text/php charset=utf-8");
echo serialize($results);
break;
}

$res = mysql_query($query);
$results = array();
$i = 0;
while($row=mysql_fetch_array($res)) {
$results['body'][$i]['id'] = $row[o];
$results['body'][$i]['category_name'] = $row[1];
$results['body'][$i]['category_spam'] = $row[2];
$i++;
}
if(empty($results['body'])){
$results['head'] = Array(
'status' => '0',
'error_number' => '604',
'error_message' => 'Select Failed. '.
'Probably wrong name supplied.'
);
}
break;
Try the above code it will create $result array for your json response.
Rest everything is fine!

Related

Rearranging logic that uses multipe foreach conditions

I have some code that takes an rss feed url, expands the rss link and gets the individual links inside that feed xml. After checking if a link exists, i insert it to a table if it does not exist and do nothing if it does. However my code is becoming more unreadable and one more check that requires another foreach it shall be even more unreadable.
This is the code
public function links_cron_job(){
//Get Rss Links
$this->db->select("the_link_itself");
$query = $this->db->get_where("search_engine_links", array("link_type" => "rss"));
foreach ($query->result() as $row){
$url = $row->the_link_itself;
$rss = Feed::loadRss($url);
foreach ($rss->item as $item) {
$this->db->where('the_link_itself',$item->link);
$query3 = $this->db->get('search_engine_links');
if ($query3->num_rows() > 0){
echo 'duplicates are there';
}else{
$data = array(
'link_country' => 'usa',
'the_link_itself' => $item->link,
'link_category' => 'news_website',
'link_added_by' => 'admin',
'link_type' => 'ordinary_link',
'link_local_type' => 'news',
'link_region' => 'countrywide',
'link_city' => 'washington',
'date_added' => $item->timestamp,
'last_updated' => time()
);
$this->db->insert('search_engine_links', $data);
echo 'no duplicates are there';
}
}
}
}
What would be another approach in doing what i am doing?
Normally I would say, just enter a return. But in this case you still might have
work to do in the extra iterations. So in this case at least we know that we are
done with this iteration, so at least we can add a continue statement:
<?php
foreach ($rss->item as $item) {
$this->db->where('the_link_itself',$item->link);
$query3 = $this->db->get('search_engine_links');
if ($query3->num_rows() > 0) {
echo 'duplicates are there';
continue;
}
$data = array(
'link_country' => 'usa',
'the_link_itself' => $item->link,
'link_category' => 'news_website',
'link_added_by' => 'admin',
'link_type' => 'ordinary_link',
'link_local_type' => 'news',
'link_region' => 'countrywide',
'link_city' => 'washington',
'date_added' => $item->timestamp,
'last_updated' => time()
);
$this->db->insert('search_engine_links', $data);
echo 'no duplicates are there';
}

get string when trying to make a dynamic json list / array

I am trying to make a dynamic JSON array in PHP, however when I try to do so it returns "Array". Here is the code I am currently using:
<?php
require '../../scripts/connect.php';
$array = '';
if($result = $db->query("SELECT * FROM art") or die ($db->error)){
if($count = $result->num_rows) {
while($row = $result->fetch_object()){
$array .= array(
'title' => $row->title,
'image' => "http://www.thewebsite.com/img/2.jpg",
'rating' => 7.7,
'releaseYear' => 2003,
'genre' => array(
'0' => $row->category,
'1' => $row->subcategory
)
);
}
}
}
echo json_encode($array);
?>
Can anyone suggest how I might go about fixing this?
And if anyone has suggestions about creating a dynamic JSON array, some help would be much appreciated.
Change your declaration of $array to be an array:
$array = array();
Then in your while loop, when you add the new array to $array, push it like this:
$array[] = array('title'=>$row->title, etc...)

Solr FieldCollapsing for More Like This queries

I want to use a "More Like This" query to find similar documents and collapse those that have the same value for the field 'image'. I tried to use the Field Collapsing parameters however they do not seem to work for "More like this".
Below is a snippet of my code. Can you tell me how to collapse results using the "More Like This" query?
$url = "http://{$host}:{$port}/solr/{$core}/mlt";
$data = [
'stream.body' => $content,
'fl' => 'image,content,title,signature',
'start' => 0,
'order' => "score desc",
'wt' => 'json',
'mlt.fl' => 'content,title',
// these lines do nothing ---v
'group' => 'true',
'group.field' => 'image',
'group.sort' => 'impressions desc',
'group.main' => 'true'
];
$curlHandle = curl_init($url);
$options = array (
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($curlHandle , $options);
$result = json_decode(curl_exec($curlHandle));
General answer
I could not collapse results using Field Collapsing paramaters. However, I was able to achieve the desired result using CollapsingQParserPlugin.
The following filter query collapses documents on the field 'image' and selects the one with the highest value for the field 'impressions': {!collapse field=image max=impressions}
Implementation
For some reason I was not able to combine this filter query with my other filter queries under a single key as follows:
$filterQueries = [
"-signature:{$signature}",
...
"{!collapse field=image max=impressions}"
];
$data = [
...
'fq' => implode(' AND ', $filterQueries),
...
];
This produced the error: Query does not implement createWeight
My fix was to do a GET request (instead of a POST, which was done in the question above). With the GET request it is possible to have a key for each filter query: http://solr-url/mtl?...&fq=-signature%3A0&...&fq=%7B!collapse+field%3Dimage+max%3Dimpressions%7D
Below is the php solution for the snippet in the question:
$url = "http://{$host}:{$port}/solr/{$core}/mlt?"; // Note the added question mark
$data = [
'stream.body' => $content,
'fl' => 'image,content,title,signature',
'fq' => $filterQueries,
'start' => 0,
'order' => "score desc",
'wt' => 'json',
'mlt.fl' => 'content,title'
];
$params = [];
foreach ($data as $key=>$value) {
if (is_array($value)) {
foreach ($value as $subvalue) {
$subvalue = urlencode($subvalue);
$params[] = "{$key}={$subvalue}";
}
} else {
$value = urlencode($value);
$params[] = "{$key}={$value}";
}
}
$url .= implode('&', $params);
$curlHandle = curl_init($url);
$options = array ();
curl_setopt_array($curlHandle , $options);
$result = json_decode(curl_exec($curlHandle));

PHP array from mysql data - x-editable bootstrap

So I'm using x-editable for bootstrap, which is awsome for me.
With that, to return a menu for selection one needs to return an array as such to make it work:
$arr = array(
array('value' => 'Male', 'text' => 'Male'),
array('value' => 'Female', 'text' => 'Female'),
);
It's fine if you have to write it, but now I need to make this array from database output.
So for instance if I run a "while($row" loop, how is the output going to be an array like that. This is what I'm trying, but oviously failing at cause this is not working:
$query = 'SELECT id,app_name FROM apps';
$result = mysql_query($query) or bomb($s,509,addslashes($query),addslashes(mysql_error()));
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
$arr .= Array(
Array('value' => $row['id'], 'text' => $row['app_name']),
);
}
}
It's probably a silly question, so thanks in advanced.
Arrays can't be concatenated like strings.
Try something like this:
while($row = mysql_fetch_assoc($result)) {
$arr[]=Array('value' => $row['id'], 'text' => $row['app_name']);
}

PHP Api - Results/Array question

I have been looking around for PHP tutorials and I found a very detailed one that have been useful to me.
But now, I have a question. The results showed by the API are stored into a $results array. This is the code (for instance):
$fetch = mysql_fetch_row($go);
$return = Array($fetch[0],$fetch[1]);
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
My question is.. I want to display the last 10 news.. how do I do this? On normal PHP / mySQL it can be done as:
while($var = mysql_fetch_array($table)) {
echo "do something"
}
How can I make it so the $results can print multiple results?
I have tried like:
while($var = mysql_fetch_array($table)) {
$results = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
}
But this only shows me one result. If I change the $results .= Array(...) it gives error.
What can I do?
Thanks!
Edit
My function to read it doesn't read when I put it the suggested way:
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $results);
$results[] = Array(
'news' => Array (
'id' => $return[0],
'title' => $return[1]
));
That should do it.
If you are familiar with arrays, this is the equivalent of an array_push();
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
<?php
$array[] = $var;
?>
Use [] to add elements to an array:
$results = array();
while($var = mysql_fetch_array($table)) {
$results[] = Array(
'news' => Array (
'id' => $var[0],
'title' => $var[1]
));
}
}
You can then loop through the $results array. It's not an optimal structure but you should get the hang of it with this.

Categories