jquery autocomplete plugin - fetch works - fetchAll doesn't - php

If I have something like this from the server side, from a fetch:
array(1) { [0]=> array(1) { ["nome"]=> string(7) "aaaa.br" } } [{"nome":"aaaa.br"}]
The json of the above is:
[{"nome":"aaaa.br"}]
This Works:
parse: function(data) {
return $.map(eval('('+data+')'), function(result) {
return {
data: result,
value: result.nome,
result: result.nome
}
});
}
The result is parsed successfully.
If, instead of fetch, I change to fetchAll, the dump gets like this (here only the first index as example):
array(65) { [0]=> array(1) { ["nome"]=> object(stdClass)#7 (1) { ["nomeDominio"]=> string(7) "aaaa.br" } }
The json conversion of the above:
string(2632) "[{"nome":{"nomeDominio":"aaaa.br"}}
Here, the result is not successfully parsed.
So I believe something needs to be changed on the js side.
But I'm absolutely clueless.
UPDATE:
The nomeDominio is from the fetchObj PDO method, and corresponds to the column name on the database. It's a natural behaviour for fetch with PDO when FETCH::OBJ option is used.
The php part of this js is:
$keyword = addslashes($_GET["q"]);
$comandos = new ComandoController();
$arr = $comandos->recebeNomeDominios($keyword);
if(is_array($arr))
{
echo json_encode($arr);
}
public function recebeNomeDominios($keyword)
{
$DominioDao = new DominioDao();
$objecto = $DominioDao->recebeNomeDominios($keyword);
return $this->jsonArray($objecto);
}
private function jsonArray($objecto)
{
$json = array();
if(isset($objecto) && !empty($objecto))
{
foreach($objecto as $obj)
{
$json[] = array('nome' => $obj);
}
}
return $json;
}
Finally:
public function recebeNomeDominios($keyword)
{
try
{
$stmt = $this->_dbh->prepare("SELECT d.nomeDominio FROM dominio d WHERE d.nomeDominio LIKE '%".$keyword."%'");
$stmt->execute();
$resultado = $stmt->fetch(PDO::FETCH_OBJ);
return $resultado;
}
catch (PDOException $ex)
{
echo "Erro: " . $ex->getMessage();
}
}
Any advice?
MEM

$comandos = new ComandoController();
$arr = $comandos->recebeNomeDominios($keyword);
echo json_encode($arr);
class ComandoController {
public function recebeNomeDominios($keyword)
{
$stmt = $this->_dbh->prepare('
SELECT
d.nomeDominio as nome
FROM
dominio
WHERE nomeDominio LIKE :keyword
');
$stmt->bindParam(':keyword', $keyparam);
$keyparam = '%'.str_replace('%', '\\%', $keyword) . '%';
$stmt->execute();
return $stmt->fetchALL(PDO::FETCH_ASSOC);
}
...

If you return one array (fetch) then you need to collect data from it like this
var name = data.name;
var age = data.age;
var gender = data.gender;
// Do something with values here
If you are using fetchAll, this will presumably return an array of arrays (a multidimensional array) which you will need to iterate over. From looking at $.map it looks like your using jQuery. Iterate over the multidimensional array like this
jQuery.each(data, function() {
name = this.name;
age = this.age;
gender = this.gender;
// Do something with values here
});

Related

Combine Sub-array values into a single array withing an array

I may not word this issue properly, so here's what am trying to achieve.
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 }
}
[1]=> {
["Abilities"]=> { ["Verbal"]=> 1 }
}
[2]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
to
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 ["Verbal"]=> 1 }
}
[1]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
I get this array from an external source so I need optimized this way to use it.
The array you're getting from an external source is like a set of separate branches you need to merge into a single tree. You can use a recursive function to create the "optimized" structure you're going for. A recursive approach should work regardless of the depth of each branch.
function merge_branches(array $branches): array
{
$merge = function ($node, &$tree) use (&$merge) {
if (is_array($value = reset($node))) {
$merge($value, $tree[key($node)]); // merge branch node recursively
} else {
$tree[key($node)] = $value; // set leaf node to value
}
};
$tree = [];
foreach ($branches as $branch) {
$merge($branch, $tree);
}
return $tree;
}
$optimized = merge_branches($external);

PHP Display The Array Index of Object

Following code
echo '<pre>';
foreach($this->allcategories as $k){
var_dump($k);
}
is displaying
object(Application_Model_Categories {
["_data":"Application_Model_Base":private]=> array(7) {
["CategoriesName"]=> string(8) "Clothing"
}
}
but I need just the CategoriesName i.e Clothing, nothing else.
Write this in your class
public function getX(){
return $this->_data;
}
And call this from where you want the data.
$data = $this->getX();
echo $data["CategoriesName"];
This should only print "Clothing":
foreach($this->allcategories as $k){
$cat = $k['CategoriesName'];
var_dump($cat);
}

Recursive function with unknown depth of values. Return all values (undefined depth)

I have a question about a recursive PHP function.
I have an array of ID’s and a function, returning an array of „child id’s“ for the given id.
public function getChildId($id) {
…
//do some stuff in db
…
return childids;
}
One childid can have childids, too!
Now, I want to have an recursive function, collecting all the childids.
I have an array with ids like this:
$myIds = array("1111“,"2222“,"3333“,“4444“,…);
and a funktion:
function getAll($myIds) {
}
What I want: I want an array, containing all the id’s (including an unknown level of childids) on the same level of my array. As long as the getChildId($id)-function is returning ID’s…
I started with my function like this:
function getAll($myIds) {
$allIds = $myIds;
foreach($myIds as $mId) {
$childids = getChildId($mId);
foreach($childids as $sId) {
array_push($allIds, $sId);
//here is my problem.
//what do I have to do, to make this function rekursive to
//search for all the childids?
}
}
return $allIds;
}
I tried a lot of things, but nothing worked. Can you help me?
Assuming a flat array as in your example, you simply need to call a function that checks each array element to determine if its an array. If it is, the function calls it itself, if not the array element is appended to a result array. Here's an example:
$foo = array(1,2,3,
array(4,5,
array(6,7,
array(8,9,10)
)
),
11,12
);
$bar = array();
recurse($foo,$bar);
function recurse($a,&$bar){
foreach($a as $e){
if(is_array($e)){
recurse($e,$bar);
}else{
$bar[] = $e;
}
}
}
var_dump($bar);
DEMO
I think this code should do the trick
function getAll($myIds) {
$allIds = Array();
foreach($myIds as $mId) {
array_push($allIds, $mId);
$subids = getSubId($mId);
foreach($subids as $sId) {
$nestedIds = getAll($sId);
$allIds = array_merge($allIds, $nestedIds);
}
}
return $allIds;
}

get data in object - SimpleXML

So I got a simple function that works, but I'm trying to evolve my experince wtih OOP and try to make sure I can use my code without having to edit everything.
Here is my simple function
$xmlfeed = file_get_contents('/forum/syndication.php?limit=3');
$xml = new SimpleXMLElement($xmlfeed);
$result = $xml->xpath('channel/item/title');
while(list( , $node) = each($result)) {
echo $node;
}
Now so far I got to this point:
class ForumFeed {
private function getXMLFeeds($feed = 'all'){
/*
Fetch the XML feeds
*/
$globalFeedXML = file_get_contents('/forum/syndication.php?limit=3');
$newsFeedXML = file_get_contents('/forum/syndication.php?fid=4&limit=3');
/*
Turn feed strings into actual objects
*/
$globalFeed = new SimpleXMLElement($globalFeedXML);
$newsFeed = new SimpleXMLElement($newsFeedXML);
/*
Return requested feed
*/
if ($feed == 'news') {
return $newsFeed;
} else if ($feed == 'all') {
return $globalFeed;
} else {
return false;
}
}
public function formatFeeds($feed) {
/*
Format Feeds for displayable content..
For now we're only interested in the titles of each feed
*/
$getFeed = $this->getXMLFeeds($feed);
return $getFeed->xpath('channel/item/title');
}
}
$feeds = new ForumFeed();
However when trying to echo $feeds->formatFeeds('all'); it doesn't return anything. The results is blank.
What am I doing wrong?
var_dump($feeds->formatFeeds('all')); returns
array(3) {
[0]=>
object(SimpleXMLElement)#3 (0) {
}
[1]=>
object(SimpleXMLElement)#4 (0) {
}
[2]=>
object(SimpleXMLElement)#5 (0) {
}
}
According to PHPs documentation SimpleXMLElement::xpath returns an array of SimpleXMLElements or false on error. Maybe var_dump($feeds->formatFeeds('all')); prints something you then can use to debug.
Edit: The XPath query returns results, so probably there is a logical error in your query or the returned elements don't have content.

mongodb php get array value

I am trying to get ONE value from a sub document of a stored doc.
a sample document looks like this and I'm trying to get the value "doc2":
{
"_id" : ObjectId("52060cae8b080ed4170063d3"),
"form_id" : "5204c6dca0875b6a1545f436",
"update" : false,
"values" : [{
"5204c71a8b080e6c190000bb" : "doc2"
}, {
"5204c7638b080e6c19006b06" : "that one too"
}, {
"form_id" : "5204c6dca0875b6a1545f436"
}, {
"btn_submit" : "Save"
}]
}
so far my code looks like this:
try {
$connection = new Mongo();
$database = $connection->selectDB('forms');
$collection = $database->selectCollection('instance');
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$value = $collection->findOne(array('_id' =>new MongoId($instid)),array('values.'.$fid));
$instid is passed in and is form_id in the document. And $fid is passed in and is the key in the values array in the document
and I'm getting this:
{ ["_id"]=> object(MongoId)#15 (1)
{ ["$id"]=> "52060cae8b080ed4170063d3" }
["values"]=>
{ [0]=> { ["5204c71a8b080e6c190000bb"]=> "doc2" }
[1]=> array(0) { }
[2]=> array(0) { }
[3]=> array(0) { }
} }
Thanks in advance for any assistance.
You are getting data in form of multidimensional Array, So you should use
print_r($value['values']['0']);
This will return
Array ( [5204c71a8b080e6c190000bb] => doc2 )
And if you only want to echo out doc2 then you can use foreach statement
foreach($value['values']['0'] as $x)
{
echo $x;
}

Categories