I created this code, but obviously it's not working. I feel there is a mistake somewhere in the logic but I don't see it.
`<?php
$languages = array(
"en" => array("name" => "English", "selector" => "/en/", "image" => "en.png"),
"fr" => array("name" => "French", "selector" => "/fr/", "image" => "fr.png"),
"de" => array("name" => "German", "selector" => "/de/", "image" => "de.png"),
"it" => array("name" => "Italian", "selector" => "/it/", "image" => "it.png"),
"si" => array("name" => "Slovene", "selector" => "/si/", "image" => "si.png"),
"es" => array("name" => "Spain", "selector" => "/es/", "image" => "es.png")
);
$current_url = $_SERVER['REQUEST_URI'];
$current_language = "";
foreach ($languages as $code => $language) {
if (strpos($current_url, $language['selector']) === 0) {
$current_language = $code;
break;
}
}
?>
<div id="language-menu">
<ul>
<?php
foreach($languages as $code => $language){
$new_url = str_replace($languages[$current_language]['selector'], $language['selector'], $current_url);
if($code === $current_language){
echo '<li class="active">'.$language['name'].'</li>';
} else {
echo '<li>'.$language['name'].'</li>';
}
}
?>
</ul>
</div>`
I expect to have a browsing between different version of the same page, where I don't know the url and the name of the page itself
Related
I am trying to implement a decision tree based on this jQuery plugin.
It expects data in this format:
$tree = array(
"href" => "/",
"label" => "Title",
"nodes" => array(
array(
"href" => "/q1",
"label" => "Question 1?",
"nodes" => array(
array(
"href" => "/q1/a1",
"label" => "Answer 1",
"nodes" => array(
"href" => "/q1/a1/q11",
"label" => "Question 1.1?",
"nodes" => array(
array(
"href" => "/q1/a1/q11/a11",
"label" => "Answer 1.1",
"nodes" => null
),
array(
"href" => "/q1/a1/q11/a12",
"label" => "Answer 1.1",
"nodes" => null
)
)
)
),
array(
"href" => "/q1/a2",
"label" => "Answer 2",
"nodes" => null
)
)
)
)
);
I fetch the results as a flat list from a database and then am able to generate the tree structure using a recursive function:
function buildTree(array $elements, $rootId = 0, $current_path = '', $new_path = '') {
$ctr = 0;
$branch = array();
foreach($elements as $element) {
if ($element['root_id'] == $rootId) {
$array = array(
'root_id' => $element['root_id'],
'label' => $element['label'],
'text' => $element['text'],
);
if(!empty($current_path)){
$path = $current_path . ++$ctr;
$array['href'] = $path;
}
$new_path = $new_path == '/q' ? '/a' : '/q';
$children = buildTree($elements, $element['id'], $path . $new_path, $new_path);
if ($children) {
$array['nodes'] = $children;
}
$branch[] = $array;
}
}
return $branch;
}
$tree = buildTree($results);
which yields:
$tree = array(
"href" => "/",
"label" => "Title",
"nodes" => array(
array(
"href" => "/q1",
"label" => "Question 1?",
"nodes" => array(
array(
"href" => "/q1/a1",
"label" => "Answer 1",
"nodes" => array(
"href" => "/q1/a1/q1",
"label" => "Question 1.1?",
"nodes" => array(
array(
"href" => "/q1/a1/q1/a1",
"label" => "Answer 1.1",
"nodes" => null
),
array(
"href" => "/q1/a1/q1/a1",
"label" => "Answer 1.1",
"nodes" => null
)
)
)
),
array(
"href" => "/q1/a2",
"label" => "Answer 2",
"nodes" => null
)
)
)
)
);
which gives the correct 'href's up to a depth of 2 but then deviates from the expected format.
I can't figure out how to get the 'href's correct.
How can i generate the correct 'href' using my recursive function as expected by the jQuery plugin?
$path = $current_path . ++$ctr;
You're counting yet this value is localized for that particular function even on recursion. It will never and seems to never move above 1 because after it iterates once, it calls buildTree again.
Is q11 not stored in the database? You need a way of incrementing/parsing/gathering (i am not sure exactly what the value should be) that value to what it should be as it recurses through. Should this value just remove the . from 1.1 ?
Try dropping in this function in place of yours and see if it changes anything:
function buildTree(array $elements, $rootId = 0, $current_path = '', $new_path = '', $parent_id = 0, $ctr = 0) {
$branch = array();
foreach($elements as $element) {
if ($element['root_id'] == $rootId) {
$array = array(
'root_id' => $element['root_id'],
'label' => $element['label'],
'text' => $element['text'],
);
if(!empty($current_path)){
if($parent_id > 0 ) {
$path = $current_path . $parent_id . $ctr;
}else{
$path = $current_path . ++$ctr;
}
$array['href'] = $path;
}
$new_path = $new_path == '/q' ? '/a' : '/q';
$parent_id++;
$children = buildTree($elements, $element['id'], $path . $new_path, $new_path, $parent_id, $ctr);
$parent_id--;
if ($children) {
$array['nodes'] = $children;
}
$branch[] = $array;
}
}
return $branch;
}
I got a recursive function which currently echo the results. I want this function to return results and loop them with foreach inside markup.
I understand that i should use some kind of iteration for each array to get my desired result but have failed with that. Currently my code look like this(with attempts to iterate):
public static function recursiveChildCategory($categories = array(), $depth = 0, $i = 0) {
$ca = [];
// Loop through categories
foreach($categories as $key => $category){
echo str_repeat(" ", $depth);
echo "<a href='".implode('/', $category['breadcrumb'])."'>{$category['title']}</a>";
echo '<br>';
$ca[$i] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
self::recursiveChildCategory($category['child'], $depth + 1, $i++);
}
}
return $ca;
}
And incoming array to the function:
Array (
[0] => Array (
[id] => 7
[title] => Deserts
[slug] => deserts
[child] => Array (
[0] => Array (
[id] => 8
[title] => Space
[slug] => space
[child] => Array (
[0] => Array (
[id] =>
[title] =>
[slug] =>
[child] => Array ( )
)
)
)
)
)
)
Currently it just returns first level of child categories "Deserts", but nothing about "Space".
As desired result i want function to return all categories with $depth and infinite path to multiple child categoires (to do the same work as currently echo doing).
Thanks in advice
Try this and tell me if it's what you are looking for :
The array for my test :
$array = [
0 => [
"id" => 7,
"title" => "Deserts",
"slug" => "deserts",
"child" => [
0 => [
"id" => 8,
"title" => "Space",
"slug" => "space",
"child" => [
0 => [
"id" => 9,
"title" => "Test",
"slug" => "test"
]
]
]
]
]
];
The recursive function :
function recursiveChildCategory($categories, $depth = 0, $ca = []) {
// Loop through categories
foreach($categories as $key => $category){
$ca[$depth] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
$ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
} else {
break;
}
}
return $ca;
}
Now, how to use it :
$test = recursiveChildCategory($array);
var_dump($test);
And this is the output :
array(3) {
[0]=>
array(2) {
["id"]=>
int(7)
["title"]=>
string(7) "Deserts"
}
[1]=>
array(2) {
["id"]=>
int(8)
["title"]=>
string(5) "Space"
}
[2]=>
array(2) {
["id"]=>
int(9)
["title"]=>
string(4) "Test"
}
}
Here is a link to test it : http://sandbox.onlinephpfunctions.com/
EDIT : I made some modification because in OP example array can have multiple result in first "depth", here is the "new" solution :
The array for test :
$array = [
"0" =>
[ "id" => 3, "title" => "Subcat", "slug" => "subcat", "child" =>
[ "0" =>
[ "id" => 5, "title" => "Subsubcat2", "slug" => "subcat2", "child" =>
[ "0" =>
[ "id" => "", "title" => "", "slug" =>"", "breadcrumb" => [ "0" => "homeworld", "1" => "cat", "2" => "subcat", "3" => "subcat2" ], "child" => [ ] ]
]
]
]
],
"1" =>
[ "id" => 4, "title" => "Kalahari", "slug" => "kalahari", "child" =>
[ "0" => [ "id" => 7, "title" => "deserts", "slug" => "deserts", "child" =>
[ "0" =>
[ "id" => 8, "title" => "Ural", "slug" => "ural", "child" =>
[ "0" => [ "id" =>"", "title" =>"", "slug" =>"", "child" => [ ] ] ]
]
]
]
]
]
];
The function : I just add $ca[$depth][] instead of $ca[$depth]
function recursiveChildCategory($categories, $depth = 0, $ca = []) {
// Loop through categories
foreach($categories as $key => $category){
$ca[$depth][] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
$ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
} else {
break;
}
}
return $ca;
}
And now the result :
$test = recursiveChildCategory($array);
foreach ($test as $depth => $c) {
echo "depth : ".$depth."\n";
foreach ($c as $result) {
echo "Title : ".$result['title']."\n";
}
echo "=============\n";
}
The output is :
depth : 0
Title : Subcat
Title : Kalahari
=============
depth : 1
Title : Subsubcat2
Title : deserts
=============
depth : 2
Title :
Title : Ural
=============
depth : 3
Title :
=============
Test here : link
I was trying to get the same result in two places with this code by including it with include(""); but after the first include goes right the second one gives me the last element of the array I made, the array is this one:
<?php
$aMenu = array(
array(
"title" => "Home",
"page" => "home",
),
array(
"title" => "Over mijzelf",
"page" => "mijzelf",
),
array(
"title" => "PC Games",
"page" => "games",
),
array(
"title" => "Video's maken",
"page" => "videos",
),
array(
"title" => "Basketball",
"page" => "basketball",
),
array(
"title" => "Fitness",
"page" => "fitness"
),
array(
"title" => "Toekomst",
"page" => "toekomst"
),
);
I call it here
foreach($aMenu as $aMenu) {
$sClass = '';
if ($aMenu["page"] == $_GET['page']) {
$sClass = 'class = "active" ';
}
/*echo $aMenu["title"];
echo $aMenu["page"];*/
echo '
<ul class=" nav nav-pills nav-stacked">
<li class="'.$sClass.'" role="presentation" >'.$aMenu["title"].'</li>
</ul>';
}
You overwrite your array while iterating:
foreach($aMenu as $aMenu)
Write something like this
foreach($aMenu as $entry)
so your iteration variable won't overwrite the array itself.
I'm trying search process input with php and send to json
the json output like this:
{
"err": 0,
"msg": "",
"data": {
"f": 0,
"hotel": [
{
"att": 25147,
"name": "Crowne Plaza Changi Airport",
"city": "Singapore",
"country": "Singapore"
}
],
"city": [
{
"att": "-2679652",
"name": "Singapore",
"region": "",
"country": "Singapore",
"nr_hotels": ""
}
]
}
}
i was trying with test array but not work
<?
$query = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%" OR city LIKE "%'.$q.'%")';
$result=mysql_query($query);
// Do Search
$json_array = array();
while ($search=mysql_fetch_array($result)){
$search_array = array(
"err"=>"","msg"=>"",
"hotel" => array(
"att" => $search['hotel_id'],
"name" => $search['hotel_name'],
"city" => $search['city'],
"country" => $search['country']),
"city"=> array(
"att"=> $search['hotel_id'],
"name" => $search['city'],
"country" => $search['country'])
);
array_push($json_array,$search_array);
}
echo json_encode($json_array);
?>
i change with this , but show only 1 record not all similar from key search
$query = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%" OR city LIKE "%'.$q.'%")';
$result=mysql_query($query);
// Do Search
$json_array = array();
while ($hasil=mysql_fetch_array($result)){
$search_array = array(
"err"=>intval("0"),"msg"=>"","data"=>array("f"=>intval("114"),
"hotel"=>array(
$hotel_array = array(
"att"=> $hasil['hotel_id'],
"name" => $hasil['hotel_name'],
"city" => $hasil['city'],
"country" => $hasil['country']
)),
"city"=>array(
$city_array = array(
"att"=> $hasil['hotel_id'],
"name" => $hasil['city'],
"city" => $hasil['city'],
))
));
}
echo json_encode($search_array);
?>
please help how the syntax for array thank
it's similar process with this site http://www.myhotelfinder.com/id/home/dohttp/predict?q=singapore
thank you this json output what i mean
<?
$query = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%" OR city LIKE "%'.$q.'%")';
$result=mysql_query($query);
// Do Search
$json_array = array(
"err" => "",
"msg" => "",
"data" => array(
"f" => 0,
"hotel" => array(),
"city" => array()
)
);
while ($hasil=mysql_fetch_array($result)){
$hotel = array(
"att" => $hasil['hotel_id'],
"name" => $hasil['hotel_name'],
"city" => $hasil['city'],
"country" => $hasil['country']
);
$city = array(
"att"=> $hasil['hotel_id'],
"name" => $hasil['city'],
"country" => $hasil['country']
);
array_push($json_array["data"]["hotel"], $hotel);
array_push($json_array["data"]["city"], $city);
}
echo json_encode($json_array);
?>
kiss ^^
I think you are asking how you need to format your array within the while block in order to achieve the JSON output.
I think you could try the following array declaration:
<?
$query = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%" OR city LIKE "%'.$q.'%")';
$result=mysql_query($query);
// Do Search
$json_array = array();
while ($search=mysql_fetch_array($result)){
$search_array = array(
"err" => "",
"msg" => "",
"data" => array(
"f" => 0,
"hotel" => array(
"att" => $search['hotel_id'],
"name" => $search['hotel_name'],
"city" => $search['city'],
"country" => $search['country']
),
"city" => array(
"att"=> $search['hotel_id'],
"name" => $search['city'],
"country" => $search['country']
)
)
);
array_push($json_array,$search_array);
}
echo json_encode($json_array);
?>
UPDATE:
Ok, I am starting to see a but more what you might be doing. Try the following:
<?
$query = 'SELECT * FROM hotel WHERE (hotel_name LIKE "%'.$q.'%" OR city LIKE "%'.$q.'%")';
$result=mysql_query($query);
// Do Search
$json_array = array(
"err" => "",
"msg" => "",
"data" => array(
"f" => 0,
"hotel" => array(),
"city" => array()
)
);
while ($hasil=mysql_fetch_array($result)){
$hotel = array(
"att" => $hasil['hotel_id'],
"name" => $hasil['hotel_name'],
"city" => $hasil['city'],
"country" => $hasil['country']
);
$city = array(
"att"=> $hasil['hotel_id'],
"name" => $hasil['city'],
"country" => $hasil['country']
);
array_push($json_array["data"]["hotel"], $hotel);
array_push($json_array["data"]["city"], $city);
}
echo json_encode($json_array);
?>
I have been fiddling around with a third-party script for some time when I noticed there was some unusual PHPBB framework code put in randomly with the rest of the PHP. What I need to understand is if there is anything particularly special about this code(can it do something regular PHP can't?) and how I can smoothly transition the code to PHP without a framework if there isn't anything special about the code.
<?
include('bar.php');
include "../includes/config.inc.php";
include "loggedin.inc.php";
include "../includes/countries.inc.php";
$auction_id = isset($_REQUEST['aid']) ? $_REQUEST['aid'] : "";
?>
<?
define("DATAGRID_DIR", "../datagrid/");
define("PEAR_DIR", "../datagrid/pear/");
require_once(DATAGRID_DIR . 'datagrid.class.php');
require_once(PEAR_DIR . 'PEAR.php');
require_once(PEAR_DIR . 'DB.php');
$DB_USER = $DbUser;
$DB_PASS = $DbPassword;
$DB_HOST = $DbHost;
$DB_NAME = $DbDatabase;
ob_start();
$db_conn = DB::factory('mysql');
$result_conn = $db_conn->connect(DB::parseDSN('mysql://' . $DB_USER . ':' . $DB_PASS . '#' . $DB_HOST . '/' . $DB_NAME));
if (DB::isError($result_conn)) {
die($result_conn->getDebugInfo());
}
$sql = "SELECT u.id, u.nick, COUNT(b.bidder) AS bid_count, 'View offers' AS link
FROM BPLA_bids b
INNER JOIN BPLA_users u ON b.bidder=u.id
WHERE b.auction=$auction_id
GROUP BY b.bidder";
$unique_prefix = "au_";
$dgrid = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
$default_order_field = "nick";
$default_order_type = "ASC";
$dgrid->dataSource($db_conn, $sql, $default_order_field, $default_order_type);
$dg_language = "en";
$dgrid->setInterfaceLang($dg_language);
$direction = "ltr";
$dgrid->setDirection($direction);
$modes = array(
"add" => array(
"view" => false,
"edit" => false,
"type" => "link"
),
"edit" => array(
"view" => false,
"edit" => false,
"type" => "link",
"byFieldValue" => ""
),
"cancel" => array(
"view" => false,
"edit" => false,
"type" => "link"
),
"details" => array(
"view" => false,
"edit" => false,
"type" => "link"
),
"delete" => array(
"view" => false,
"edit" => false,
"type" => "image"
)
);
$dgrid->setModes($modes);
$http_get_vars = array(
"aid"
);
$dgrid->setHttpGetVars($http_get_vars);
$printing_option = false;
$dgrid->allowPrinting($printing_option);
$exporting_option = false;
$exporting_directory = "";
$dgrid->allowExporting($exporting_option, $exporting_directory);
$sorting_option = true;
$dgrid->allowSorting($sorting_option);
$paging_option = true;
$rows_numeration = false;
$numeration_sign = "N #";
$dgrid->allowPaging($paging_option, $rows_numeration, $numeration_sign);
$bottom_paging = array();
$top_paging = array();
$pages_array = array(
"10" => "10",
"25" => "25",
"50" => "50",
"100" => "100",
"250" => "250"
);
$default_page_size = 10;
$paging_arrows = array(
"first" => "|<<",
"previous" => "<<",
"next" => ">>",
"last" => ">>|"
);
$dgrid->setPagingSettings($bottom_paging, $top_paging, $pages_array, $default_page_size, $paging_arrows);
$dgrid->setViewModeTableProperties($vm_table_properties);
$vm_colimns = array(
"nick" => array(
"header" => "Nick",
"type" => "label",
"summarize" => "false",
"visible" => "true"
),
"bid_count" => array(
"header" => "Bid count",
"type" => "label",
"summarize" => "false",
"visible" => "true"
),
"link" => array(
"header" => " ",
"type" => "link",
"field_key" => "id",
"field_data" => "link",
"href" => "auction_users_bids.php?aid=$auction_id&uid={0}"
)
);
$dgrid->setColumnsInViewMode($vm_colimns);
$dgrid->bind();
ob_end_flush();
?>
PHPBB uses standard PHP code. In the code you display, a DataGrid class is used, which PHPBB defined earlier. If you can find where that class is defined, that may help in understanding what it is doing. Search for
class DataGrid
in the PHPBB code to find out more about that class.