combining values from mysql seperated by comma using explode - php

I have two columns in my mysql table pro_id and pro_page. Each column contains integer values separated by comma.
example,
pro_id pro_page
-------- ------------
1,2,3 1,1,1
2 1
3,4 2,1
I want to combine first integer value from pro_id and first integer value from pro_page, second integer value from pro_id and second integer value from pro_page and so on.
For example,
from first row, result should be 11 21 31
from second row, result should be 21
from third row, result should be 32 41
I have tried using the below code,
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++)
{
$pro_id = explode(",", #$pro_id[$i]);
$pro_page = explode(",", #$pro_page[$i]);
foreach($pro_id as $product_id) {
$product_id = $product_id;
echo $product_id;
}
foreach($pro_page as $product_page) {
echo $product_page;
}
}
Now the result is,
from first row, 123111
from second row, 21
from third row, 3421
Is there any way to achieve what i want. I have tried a lot.

After fetching the array from database do the following:
$output = array();
while($row = mysqli_fetch_array($result1))
{
$pro_id = explode(',' , $row["pro_id"]);
$pro_page = explode(',' , $row['pro_page']);
for($i = 0; $i< count($pro_id); $i++)
{
$output[$i] = $pro_id[$i] . $pro_page[$i];
}
return $output;
}

You can do it via single foreach if you numbers amount is same in both arrays
$products = explode(",", #$pro_id[$i]);
$pages = explode(",", #$pro_page[$i]);
foreach( $products as $k => $product_id){
$product_page = $pages[$k];
echo $product_id . $product_page . " ";
}

Try below code:
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++){
$pro_id = explode(",", #$pro_id[$i]);
$pro_page = explode(",", #$pro_page[$i]);
$newProduct_id = '';
foreach($pro_id AS $keyIndex => $product_id) {
$newProduct_id = $pro_id[$keyIndex] . $pro_page[$keyIndex] . " ";
echo $newProduct_id;
}
}

You have to loop over both arrays at once. Easiest when using for():
$query = "SELECT pro_id, pro_page from tbl_checkout";
$result = mysqli_query($c,$query)or die(mysqli_error($c));
$length = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result1))
{
$pro_id[] = $row["pro_id"];
$pro_page[] = $row['pro_page'];
}
for($i=0; $i<$length1; $i++)
{
// don't assign to $pro_id and $pro_page as variable name: it will mess up your data!
$tmp_id = explode(",", $pro_id[$i]);
$tmp_page = explode(",", $pro_page[$i]);
for($c=0; $c < count($tmp_id)) {
echo $tmp_id[$c];
echo $tmp_page[$c];
}
}
Another problerm is that you use $pro_id and $pro_page for two different purposes. You use it for storage of db results and to store the exploded numbers from this data. Use different variable names.

Related

How to store or push array of objects

I need to store service_ids and country_ids in an array in this format
array
[0]["service_id"] should give service id at 0th
index
array[0]["country_id"] should give me country id at 0th index and so on.
function service_ids($conn) {
$ids = array();
$sql = "SELECT id from services";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$service_ids = service_ids($conn);
function country_ids($conn) {
$ids = array();
$sql = "SELECT id FROM countries";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$country_ids = country_ids($conn);
`//I am having problem here how to store it.
$z = array();
for ($i=0; $i < count($service_ids); $i++) {
$z = array(`
array("service_id"=>$service_ids[$i], "country_id"=>$country_ids[$i])
);
}
print_r($z);
?>
You are basically overwriting array in each iteration in final loop, instead of that store new array in new array index
$z = array();
$counter = 0;
for ($i=0; $i < count($service_ids); $i++) {
$counter = count($z);
$z[$counter]["service_id"] = $service_ids[$i];
$z[$counter]["country_id"] = $country_ids[$i];
}

Setting up array key/value pairs and accessing

I have set up an array called $compData by importing data from MySql and pushing two separate arrays called $yearsArray and $salesArray into $compData. Before pushing these two arrays to $compData I have first set their ['name'] to 'Year' and 'Sales', respectively. The code for this is included below.
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'ID_YEAR'");
$yearsArray = array();
$yearsArray['name'] = 'Year';
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$yearsArray['data'][] = $r["Year$n"];
}
}
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'IS_SALES'");
$salesArray = array();
$salesArray['name'] = 'Sales';
while($rr = mysqli_fetch_assoc($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$salesArray['data'][] = $rr["Year$n"];
}
}
$compData = array();
array_push($compData,$yearsArray); // 0
array_push($compData,$salesArray); // 1
Now I want to access and echo the data in $compData by using the code below, but this doesn't work. I am not very comfortable with PHP and am wondering if I am not using the ['Year'] and ['Sales'] identifiers correctly. Any help is much appreciated.
foreach($compData['Year'] as $result) {
echo $result, '<br>';
}
foreach($compData['Sales'] as $result) {
echo $result, '<br>';
}
You've set 'Year' as the value of key 'name', but try to use it as key (of another array).
Now you have
echo $compData[0]['name']; // -> 'Year'
echo $compData[1]['name']; // -> 'Sales'
You probably want
$compData = array();
$compData['Year'] = $yearsArray;
$compData['Sales'] = $salesArray;
instead of the array_push..

array_merge() How can I add a 'range' of an array name

I have a $nr variable that as the number of arrays with the same name that i created in a previous function, something like this:
$var = 'sorteios_'.$nr;
$$var = array($sorteio_id);
I have it in a While function so it was created something like 3 arrays with the names:
$sorteios_1 , $sorteios_2 , $sorteios_3
And i want to add them inside an array_merge, so i have to use the $nr that says how many arrays with the same name were created.
$nr = 3;
i want that the final result looks something like this.
$result = array_merge($sorteios_1, $sorteios_2, $sorteios_3);
That's the whole function if you want to check it (it's not complete because of the problem i'm having):
function check_sorteios(){
global $db;
$id = $_SESSION['userid'];
$query1 = "SELECT * FROM sorteios WHERE userid = $id";
$result1 = $db->query($query1);
$count = $result1->rowCount();
if ($count == 0){ $sorteios = 0; echo "sem sorteios";}
else{
$numero = 0;
$sorteios = 0;
$nr = 0;
while($row1 = $result1->fetch()){
if ( $numero == $count ){ return 0;}
$numero++;
$sorteio_id = $row1['id'];
$query2 = "SELECT * FROM productos WHERE id = $sorteio_id";
$result2 = $db->query($query2);
while($row2 = $result2->fetch()){
$data = $row2['data'];
$titulo = $row2['titulo'];
if (strtotime($data) > time()){
if(!isset($$sorteio_id)){
$$sorteio_id = 1;
}
$nr++;
$var = 'sorteios_'.$nr;
$$var = array($sorteio_id);
}
}
}
}
$result = array_merge($sorteios_1, $sorteios_2, $sorteios_3);
$occurences = array_count_values($result);
print_r($occurences);
}
You could try to create a string containing the code executing array_merge of all your arrays and then pass it to the eval function (http://it1.php.net/manual/it/function.eval.php)...
Something like this:
$str="\$result=array_merge(";
for($i=1;$i<=$nr;$i++){
$str.="\$sorteios_$i,";
}
$str=substr($str,0,-1);
$str.=");";
eval($str);
Then in $result you have what you need.
Is there a reason you can't recursively merge?
if ($nr > 0) {
$result = $sorteios_1;
for ($i = 2; $i <= $nr; ++$i) {
$result = array_merge($result, ${'sorteios_'.$i});
}
} else {
// you might want to handle this case differently
$result = array();
}

Notice: Array to string conversion - PHP & mySQL

I've been reading in every thread in here that is related to this but I always get it wrong.
Please help cause I always get the error
"Notice: Array to string conversion" in line "$address[] =
mysql_result($row, 0 );"
below. Please help.
if ($p_address=mysql_query($email))
{
$address = array();
while($row = mysql_fetch_assoc($p_address))
{
$address[] = mysql_result($row, 0 );
}
$all_address = implode(',', $address);
Change this line
$address[] = mysql_result($row, 0 );
To this:
$address[] = $row;
And then to see the keys and values available in the new $address array, you can do something like this:
print_r($address);
In order to keep implode() functional, do something like this:
for ($i = 0; $i < count($address); $i++) {
$all_address[] = implode(',', $address[$i]);
}
Final output:
if ($p_address=mysql_query($email))
{
$address = array();
while($row = mysql_fetch_assoc($p_address))
{
$address[] = $row;
}
for ($i = 0; $i < count($address); $i++) {
$all_address[] = implode(',', $address[$i]);
}
// Example for outputting on screen:
foreach ($all_address as $aa) {
print $aa . "<br/>\n";
}
}
Hope that helps...
$row is set in every iteration of the while loop. every time it contains a new table record. So you just need to add each record in the address array.
while($row = mysql_fetch_assoc($p_address))
{
$address[] = $row;
}

what is wrong with this loop?

$result = mysql_query($query);
$filter = array();
while($r = mysql_fetch_array($result))
{
for ( $i = 0; $i<20; $i++)
{
$filter[] = $r["name"][$i];
}
$name = implode(",", $filter);
}
Above is a portion of main code. I want to restrict loop to run only 20 times. if above 20 it should omit...but this gives me some odd result...I know some where I made a mistake but where?
mysql_fetch_array only fetches a single row of data from the query results. It looks like you're trying to fetch only a single field from the results, so you'd want something like this:
$i = 0;
while($row = $mysql_fetch_assoc($result)) {
$i++
if ($i >= 20) {
break;
}
$filter[] = $row['name'];
}
$name = implode(",", $filter);
But this is very inefficient. Why not have MySQL do the row-limiting itself?
SELECT your,fields,here
FROM yourtable
WHERE ...
ORDER BY ...
LIMIT 20
and then you only get 20 rows to start with, without forcing mysql to fetch all however-many-there-are-beyond-20.
You are not advancing to the next row
$result = mysql_query($query);
$filter = array();
$i = 0;
while($r = mysql_fetch_array($result))
{
$filter[] = $r["name"][$i]; }
$name = implode(",", $filter);
if(++$i == 20)
{
break;
}
}

Categories