I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}
Related
I have the following function to work with:
function listBrandTopics($params){
self::_getParam($params,'article_path',Wrapper::basePath().'article/');
$articles = Array();
$first_pass = true;
$count = 0;
while($result['_links']['next'] || $first_pass){
$count++;
$first_pass = false;
$result = $this->_apiCall(
Array(
'path' => '/brands/'.$params['bid'].'/articles',
'request_param' => Array(
'per_page' => '100',
'page' => $count
)
)
)->getBody();
$result = json_decode($result, true);
$articles = array_merge($articles, array_filter($result['_embedded']['entries'], array($this, '_inSupport')));
}
array_walk($articles, Array($this, '_articlesProcessor'));
$topics = $this->_topicId();
$info = Array();
foreach($articles as $article){
$topic_id = intval($article['topic_id']);
foreach($topics as $topic){
$topic_name = trim($topic['name']);
if($topic_id == $topic['id']){
$info[$topic_name]['id'] = $topic['id'];
if(!is_array($info[$topic_name]['articles'])){
$info[$topic_name]['articles'] = Array();
}
array_push($info[$topic_name]['articles'], $article);
break;
}
}
}
$params['current_brand'] = self::$brand_table[$params['bid']];
$params['the_data'] = $info;
$params['the_data_json'] = json_encode($info);
return $this->_getHtmlTemplate(self::_getParam($params,'template','brandTopics.phtml'),$params);
}
It renders a list of topics and their related articles in a support site.
However, this list of topics is not alphabetically ordered.
I know that $topic['name'] is the name of the topic, but how do I get it to return them in alphabetical order?
Thanks for the help!
Use the function ksort to order $info by key
After:
$info = Array();
foreach($articles as $article){
...
}
Add:
ksort($info);
Use simple sort($array) for alphabetically sorted array.
$this->cars = array("bmw", "audi", "opel", "ford");
sort($this->cars);
Use asort($array) (with sort_flags) if You need to keep key/value association in order.
sort - manual
asort - manual
I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";
I have a multidimensional array, and I can not update one of these:
public function get_list($query){
if(mysql_query($query,DB::connect())){
$result = mysql_query($query);
if (mysql_affected_rows() != 0) {
while ($row = mysql_fetch_array($result)) {
$list_annunci[] = array(
"id" => $row["id"],
"title" => $row["title"]
);
if(mysql_query($immagini,DB::connect())){
$result_img = mysql_query($immagini);
if (mysql_affected_rows() != 0) {
while ($row_img = mysql_fetch_array($result_img)) {
$list_annunci[] = array(
"img" => $row_img["path_img"]
);
}
}
}
}
how do I insert the record in the array already declared?
tnx stefania
Use your ids as keys for the original array.
$list_annunci[$id] = array(
Make the database query returns those ids as well.
SELECT id, path_img
Then you can inject or update the right group.
$list_annunci[ $id ]["img"] = $row_img["path_img"];
^
|
from $row_img["id"]
Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array.
This is my code:
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
array_push($hotel_array, $hotel_array2);
}
}
In this mode I have the array hotel_array which all hotel with rooms.
The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms.
If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel.
Example now my situation is that:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
id = 1
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
[0]{
id = 1,
name = 'test'
rooms{
id = 30
}
}
}
I'd like to have this result instead:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
[0]{
id = 1
}
[1]{
id = 30
}
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
}
How to create an array like this?
Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it.
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
if (!isset($hotel_array[$hotel_array2['id']])) {
$hotel_array[$hotel_array2['id']] = $hotel_array2;
} else {
$hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']);
}
}
}
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array.
$hotels = array();
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string) $entry2->attributes()->HOTEL_CODE;
if ( empty($hotels[$id]) ) {
$hotels[$id] = array(
'id' => $id,
'name' => utf8_decode($entry2->HOTEL_NAME),
'rooms' => array(),
);
}
foreach($entry2->ROOM_DATA as $room){
$hotels[$id]['rooms'][] = array(
'id' => (string) $room->attributes()->CCHARGES_CODE;
);
}
}
}
Just in case it helps...
And this :)
$hotel_array = array();
foreach ($xml->DATA as $entry)
{
foreach ($entry->HOTEL_DATA as $entry2)
{
$hotel_code = (string) $entry2->attributes()->HOTEL_CODE;
if (false === isset($hotel_array[$hotel_code]))
{
$hotel = array(
'id' => $entry2->ID,
'code' => $hotel_code,
'name' => utf8_decode($entry2->HOTEL_NAME)
);
foreach($entry2->ROOM_DATA as $room)
{
$hotel['rooms'][] = array(
'id' => (string)$room->attributes()->CCHARGES_CODE,
);
}
$hotel_array[$hotel_code] = $hotel;
}
}
}
I have the following PHP, that needs to take a list of article ids and run it through a function to get them all from the database.
I am very much a beginner in PHP so far I have:
list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id'));
$a = array(
$item => $slide1,
"two" => $slide2,
// "three" => $slide3,
// "four" => $slide4,
// "five" => $slide5
);
foreach ($a as $k) {
$args['id'] = $k;
$item = ModArticleSlider::getArticles($args);
}
and the class:
class ModArticleSlider {
public function getArticles($args){
$db = &JFactory::getDBO();
$item = "";
$id = $args['id'];
if($id > 0){
$query = "select * ";
$query .= "FROM #__content WHERE id =".$id." AND state=1 " ;
//echo $query;
$db->setQuery($query);
$item = $db->loadObject();
}
return $item;
}
}
How would i get it so that instead of specifying $item to have it almost dynamic so that i can get all the selected articles and place them in different variables.. or would i have to place them in a array?
Any Advice/Answers Greatly Appreciated.
Another approach, and possibly more performant as it would require only one database query (versus one for each article), would be to use http://docs.joomla.org/JDatabase::loadObjectList
So, you could instead pass an array of your articles ids as $ids to your class like:
public function getArticles($ids){
if ($ids) {
$db = JFactory::getDbo();
$query = "SELECT * FROM #__content WHERE id IN (" . implode(',', $id) . ") AND state=1 " ;
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
return FALSE;
}
$rows is returned as an array so you can then process it as needed.
i am also beginner of PHP.
Please Try this:
foreach ($a as $k => $val) {
$args = $val;
$item[] = ModArticleSlider::getArticles($args);
var_dump($item);
}
in your class
simply
$id = $args;
i hope it will help you!
Store the articles into an array, you can try this:
$slides = explode(" ", $params->get('id'));
$articleArray = array();
foreach($slides as $slide) {
$articleArray[] = ModArticleSlider::getArticles($slide);
}
var_dump($articleArray);