I am working on a project that requires imploding an array with character separation. I have successfully used join and implode interchangeably in other parts of the project, but I can't get it to work in this section.
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
The result is this:
Demographics
• Affluent • Children • Hard-to-Reach • Parents
instead of
Demographics
Affluent • Children • Hard-to-Reach • Parents
I've tried using double quotes instead of single quotes around '.chr(149).'. I've tried using commas or bars or just spaces. I've tried different ways of trimming and not trimming $catdata->name.
I also thought about trying string concatenation, but then I'll end up with an extra character at the end instead of the beginning. Implode or join seem the better way to go.
What am I missing?
I am not sure I understand what you are trying to do, but why not use
$demographics_names = array();
while($catdata = $dbc->fetch($dbResult)) {
array_push($demographics_names, trim($catdata->name));
}
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
Thank you, everyone, for your help! I ended up reformatting the query and array. Here is the final code:
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
if (is_array($demographics)) {
$demographic_names[] = trim($catdata->name);
}
}
$demographics = join(' '.chr(149).' ',$demographic_names);
print $demographics;
The result is:
Demographics
Affluent • Children • Hard-to-Reach • Parents
Hopefully this will be helpful to someone else!
You're inserting a blank element into the array that you're imploding:
$demographic_names = array('',trim($catdata->name));
^--- here
Seems like you have a blank demographic_name. Use array_filter on the resulting array.
Check the first array is empty.
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
if(!empty($demographic_names))
{
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
}
Related
My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);
i wrote the following code:
<?php
$listO = $_POST["letter"];
//print_r($listO);
//Array ( [0] => A [1] => B [2] => C)
function to_pg_array($set) {
settype($set, 'array'); // can be called with a scalar or array
$result = array();
foreach ($set as $t) {
if (is_array($t)) {
$result[] = to_pg_array($t);
} else {
$t = str_replace('"', '\\"', $t); // escape double quote
if (! is_numeric($t)) // quote only non-numeric values
$t = '"' . $t . '"';
$result[] = $t;
}
}
return '{' . implode(",", $result) . '}'; // format
}
$pg_array_listO = to_pg_array($listO);
//print_r($pg_array_list_organisms);
//{"A","B","C"}
$conn = pg_connect("host=X dbname=Y user=Z");
$result = pg_query_params($conn, 'SELECT count(cp.id)
FROM cp, act, a, t
WHERE t.tid = a.tid AND
a.aid = act.aid AND
act.m = cp.m AND
t.n = $1 AND
act.st = $2 AND
t.o LIKE ANY(ARRAY[$3])', array($t1, $a2, $pg_array_listO));
while($row = pg_fetch_row($result)) {echo $row[0];}
?>
However i can't figure out how to pass the array $pg_array_listO to the postgres query. The function to_pg_array converts the php array into postgres array but still don't work. How can i do this?
postgres array looks like '{list}' :
t=# select array['a','b','c'];
array
---------
{a,b,c}
(1 row)
so you need to get rid of double quotes, otherwise postgres understands literals as identities.
Eg with $pg_array_listO = str_replace('"', '\\"',to_pg_array($listO)) or smth smarter - sorry - I'm not good in php
additionally modify ANY(ARRAY[$3]) to ANY('$3'::text[]), cos array[] or '{}'::text[] would be accepted
update
based on
//print_r($pg_array_list_organisms);
//{"A","B","C"}
I expect this to work:
$result = pg_query_params($conn, "SELECT count(cp.id)
FROM cp, act, a, t
WHERE t.tid = a.tid AND
a.aid = act.aid AND
act.m = cp.m AND
t.n = $1 AND
act.st = $2 AND
t.o LIKE ANY($3)", array($t1, $a2, str_replace('"', '',to_pg_array($listO))));
mind I changed quotes and SQL and str_replace for $3 variable
a working example of this approach:
t=# select 'a' like any('{a,b,c}'::text[]);
?column?
----------
t
(1 row)
My select query is like this, in group_name i am giving comma but I want to remove comma from last. I already tried with trim but it removes all commas, and I want to remove last comma only.
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
while($groupRow = mysql_fetch_array($selctGroupRes))
{
echo $groupRow['group_name'].',';
}
Instead of echoing out each line, build up a string to echo at the end. Before that, remove the lingering comma from the end with rtrim($str,",").
$str = "";
while($groupRow = mysql_fetch_array($selctGroupRes)) {
$str .= $groupRow['group_name'].',';
}
echo rtrim($str,",");
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
$str='';
while($groupRow = mysql_fetch_array($selctGroupRes))
{
if($str=='')
$str=$groupRow['group_name'];
else
$str.=','.$groupRow['group_name'];
}
echo $str;
Using rtrim().Like below
rtrim($groupRow['group_name'])
Store your data in array and using implode you can remove last comma
while($groupRow = mysql_fetch_array($selctGroupRes))
{
$result[] = $groupRow['group_name'];
}
echo implode(",", $result);
I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!
$result = mysql_query(" SELECT p.page_url AS url,
COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
w.word_word = \"$keyword\"
GROUP BY p.page_id
ORDER BY occurrences DESC
" );
$output = "<loginsuccess>";
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}
$output .= "</loginsuccess>";
print ($output);
I am gettign the output in XML, instead i want it in array... how to achieve this.
The code below is not working...
$ret = array();
for( $i = 1; $row = mysql_fetch_array($result); $i++ ) {
$tmp['url'] = $row['url'];
$tmp['occurrences'] = $row['occurrences'];
$ret[] = $tmp;
}
return $ret;
You're already getting the results in an array when you call mysql_fetch_array($result). That's what mysql_fetch_array does.
Unless you want some other kind of array format? If so, you'll have to be more specific.
Use print_r():
echo "<pre>";
print_r($row);
echo "</pre>";
Note: If you won't wrap it in <pre> tags, the output will be difficult to read as it will appear all on one line
A for-loop is only to be used in an incremental fashion, you attempted to use it in place of a while loop. This isn't "do 1,000 times" but "do while we have a row to use".
Try this:
while($row = mysql_fetch_array($result)) {
$tmp['url'] = $row['url'];
$tmp['occurrences'] = $row['occurrences'];
$ret[] = $tmp;
}
return $ret;
Try it like so, notice the here-doc style of writing the SQL statement. I find it very helpful. Also I would suggest rewriting the SQL to use JOINs instead of crowding the WHERE clause with join criteria.
$sql = <<<EOSQL
SELECT p.page_url AS url, COUNT(*) AS occurrences
FROM page p, word w, occurrence o
WHERE p.page_id = o.page_id AND
w.word_id = o.word_id AND
w.word_word = "$keyword"
GROUP BY p.page_id
ORDER BY occurrences DESC;
EOSQL;
$result = mysql_query($sql) or die('failed to execute the query');
while ($row = mysql_fetch_array($result)) {
print_r ($row);
}
Hope this is roughly what you're after
You need to initialize your $tmp array before using it.