I have a PDO Query that returns what appears to be an array $pds. I can loop through this array as follows:
foreach ($pds as $row) {
}
I need to loop through the same array a second time but when I do this there doesn't appear to be any data in the array. Also I've tried to copy the array as follows:
$pds2 = $pds;
Is there a trick I'm missing to use this array twice?
thx
Code:
// Remove Duplicate Locations where words are in a different order
$cityArray = $pds;
foreach ($cityArray as $data) {
$words = explode(' ', $data['city'] . ' ' . $data['region1'] . ' ' . $data['region2'] . ' ' . $data['region3']);
sort($words);
$cityWordsArray[$data['id']] = implode(' ', $words);
}
$cityWordsArray = array_unique($cityWordsArray);
foreach ($pds as $row) {
echo 'hi';
foreach($cityWordsArray as $key=>$value) {
if($row['id'] == $key) {
I'm afraid that $pds is not an array, but a PDOStatement.
If you want to get as an array, you should use fetchAll to get the result as an array.
Try $pds = $pds->fetchAll(); before the loop.
Related
I have a function for arrays that I insert in db.
$data = array(
"This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);
I formatted it correctly and given output is with:
$result = array_walk($data, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });
and the result of one of the rows that is inserted in db in JSON format is:
{ This, is, Example }, { One, Of, My, Arrays}
and all of them are formatted that way.
How can I bypass this to get desired format like:
{ This, is, Example, One, Of, My, Arrays}
If you want to convert this
$data = array(
"This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);
to this
{ This, is, Example, One, Of, My, Arrays}
you can simply do it by
$result = [];
foreach ($data as $index => $value) {
$result[] = implode(',', explode("\t", $value));
}
$result = '{' . implode(',', $result) . '}';
This it´s my little script, but don´t get right results at the moment :
<?php
// Delimiters betweeb data "*" elements in each data delimiters ","
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Explode $data_string for "~" delimiter
$data_exp=explode("*",$data_string);
//
// Loop 1
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
// We want see the elements with the same data in common in second position (403,404,etc)
$data_common_1[]=$data_exp_compar[1];
$data_common_2[]=$data_exp_compar[1];
}
$a=array_values(array_intersect_key($data_common_1,$data_common_2));
$b=array_count_values(array_intersect_key($data_common_1,$data_common_2));
foreach($a as $aa=>$values)
{
echo $aa;
print "<br>";
}
?>
The idea in this script. It scans the data inside "$data_string", as you can see, all data delimiters is "*" and inside each data we have elements with "," as delimiter
I want get this output results and in this format :
PRODUCT Id: 403 (2 Actually)
1- house1,403,phone1
2- house3,403,phone3
PRODUCT Id: 404 (1 Actually)
1 - house2,404,phone2
Product Id: 405 (1 Actually)
1 - house4,405,phone4
As you can see the only element for compare it´s in the second position and it´s product´s id
I try many things but i can´t get works, or get finally results as i want show
Thank´s in advanced for all , regards
You can group them first then another foreach loop for printing result
$data_string="house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
$data_exp = explode("*",$data_string);
$group = []; // Initialize group array
foreach($data_exp as $data_1)
{
$data_exp_compar=explode(",",$data_1);
$group[$data_exp_compar[1]][] = $data_exp_compar; // Group by the number key after exploding
}
// Loop to each group, then print desired format
foreach ($group as $key => $value) {
echo 'Product ID: ' . $key . ' (' . count($value) . ' Actually)<br>';
foreach ($value as $k => $v) {
echo ++$k . ' - ' . implode(',', $v) . '<br>';
}
echo '<br>';
}
I would suggest using array_map and array_filter functions. Let me know if you have questions about this.
<?php
// Prepare data and input
$id = 403;
$data = "house1,403,phone1*house2,404,phone2*house3,403,phone3*house4,405,phone3";
// Convert string data to array
$data = explode("*", $data);
$data = array_map(function ($row) {
return explode(",", $row);
}, $data);
// Search the array
$response = array_filter($data, function ($row) use ($id) {
return $row[1] == $id;
});
print_r($response);
I have an array like this $arr = Array ("A","E","I","O","U");
My question is using implode function how can I make the output like this
1.A
2.E
3.I
4.O
5.U
You need to iterate over each values like this:
$arr = array("A","E","I","O","U");
foreach ($arr as $key => $value) {
echo $key + 1 . ".{$value} <br>";
}
This will give you the desired Output as:
1.A
2.E
3.I
4.O
5.U
Hope this helps!
$i = 1;
foreach ($arr as $v) {
echo $i . '.' . $v . '<br>';
$i++;
}
no need to use implode function. Just use foreach loop to iterate whole array.
use array_walk to traverse the array like this:
array_walk($array, function($v, $k)
{
echo $k + 1 . '.' . $v . "<br>";
});
$keyNames = array();
$keyVals = array();
foreach ($varArray as $key => $name) {
$keyNames .= $key . ', ';
}
foreach ($varArray as $key => $val) {
$keyVals .= '\'' . $val. '\', ';
}
// build query
$sql = "INSERT INTO Organizations (";
$sql .= rtrim($keyNames, ", ");
$sql .= ") VALUES (";
$sql .= rtrim($keyVals, ", ");
$sql .= ");";
echo "<div style=\"padding:5px;background-color:#efefef\">".$sql."</div>"; // this output is working
I am trying to get the above code to work without error. IT currently works but I am getting " Array to string conversion in" error even though I am getting the result that I am expecting.
I am trying to build an sql query from array elements. Both loops throw an error but the echo SQL is giving me what I want. I just want to get rid of the error. I have tried (string) and (array) and implode() and join() but I have not been able to clear the error.
Can you point me in the right direction?
Your procedure seems quite useles because there is implode function for merging array's elements:
$keyNames = implode(',', array_keys($varArray));
$keyValues = '"' . implode('","', $varArray) . '"';
And SQL:
$sql = 'INSERT INTO Organizations (' . $keyNames . ') VALUES (' . $keyValues . ')';
The error is because you're initializing the variables as arrays, and then concatenating strings to them. What you want is:
$keyNames = implode(', ', array_keys($varArray));
$keyVals = implode(', ', array_map(function($val) {
return "'$val'";
}, array_values($varArray)));
The error comes from trying to concatenate a string onto an array. Because you are using $keyNames and $keyValues strictly as strings, there is no need to initialize them as arrays - simply use strings and the error will go away.
Change
$keyNames = array();
$keyVals = array();
to
$keyNames = $keyVals = '';
I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}