Below is my code:
$id = $_GET['id'];
$qty = $_GET['qty'];
$product_id=$_GET['product_id'];
This is how I receive in the browser
http://example.com/shopping_cart.php?id=17,18&qty=4,5&product_id=3
$_SESSION['test'][]= array('product_id'=>$product_id,array('id'=>$id,'qty'=>$qty));
//print_r($_SESSION['test']);
foreach($_SESSION['test'] as $item=>$value)
{
echo "Main Array ID=". $item;
echo "<br/>";
foreach($value as $v=>$v1)
{
if(is_array($v1))
{
echo "Sub Array ID=". $v;
echo "<br/>";
echo "size id=". $v1['id'];
echo "<br/>";
echo "Quantity=". $v1['qty'];
echo "<br/>";
}
}
}
Output:
Main Array ID=0
Sub Array ID=0
size id=12,13
Quantity=1,2
Main Array ID=1
Sub Array ID=0
size id=17,18
Quantity=4,5
Since size_id and quantity are in implode form, I mean they have a comma ',' in between the value. I need to explode them and use foreach to display one by one.
I mean something like this:
$size_id1=explode(',',$v1['qty']);
foreach($size_id1 as $size_id2)
{
echo $size_id2;
}
$qty1=explode(',',$v1['qty']);
foreach($qty1 as $qty2)
{
echo $qty2;
}
What I need is, I want to display matching size_id and qty. For example, instead of displaying:
size_id 1
size_id 2
Qty 1
Qty 2
It should display:
Size_id 1 Qty 1
Size_id 2 Qty 2
How can I achieve this?
$ids = $_GET['id']
$qtys = $_GET['qty']
$product_id = $_GET['product_id'];
$tmp_result = array();
$ids = explode(',',$ids );
$i = 0;
foreach($ids as $id)
{
$tmp_result[$i]['id'] = $id;
$i++;
}
$i = 0;
$qtys =explode(',',$qtys );
foreach($qtys as $qty)
{
$tmp_result[$i]['qty'] = $qty;
$i++;
}
$_SESSION['tmp_results'][$product_id] = $tmp_result;
$temp_arr = array();
$id_str = '17,18';
$qty_str = '4,5';
foreach(array_combine(explode(',', $id_str), explode(',', $qty_str)) as $k => $v) {
$temp_arr[]['id'] = $k;
$temp_arr[]['qty'] = $v;
}
diffrence betwen 2 implode fetch from database
<?php
$select_tbl=mysql_query("select * from user_reg where uid='". $_SESSION['user1']."'");
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->specialised;
$i=explode(",",$r);
$length = count($i);
for ($x=0; $x<$length; $x++)
{
echo $i[$x]; }
}?><tbody>
<?php
mysql_connect("localhost","root","");
mysql_select_db("freelancer");
$query=mysql_query("select * from post_proj where status = 1 and payment = '' ") or die(mysql_error());
$j = 1;
while($result=mysql_fetch_array($query))
{
if($result['uid'] == "")
{$d2 = $result['proj_skill'];
$pantry_food1 = explode(",",$d2);
$count_total1 = count($pantry_food1);
for ($counter=0; $counter<$count_total1; $counter++){
$line1 = each ($pantry_food1);
// echo $pantry_food1[$counter];
} $rrt = array_intersect($i,$pantry_food1);
Related
I've got something I think it is a 3 dimensional array:
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
So there are 2 arrays packed inside the variable. First is separated by | the second one by ,
What I need to do is: separate them and then check for an ID located before the name and give me single variables of the rest.
I tried it like this:
<?php
$personid = 3;
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
$array = explode('|',$var);
foreach($array as $values) {
$arr = explode(",",$values);
foreach($arr as $value) {
if($value[0] == $personid) {
$id = $value[0];
$name = $value[1];
$height = $value[2];
$killloop = 1;
}
}
if($killloop == 1) {
break;
}
}
echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height;
?>
But all i get then is:
ID: 3
Name:
Height:
Can anyone help out?
There is no need loop Into Second Array, You already have defined positions.
Always Use break statement to end a Loop immediately, Its a good practice
<?php
$personid = 3;
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
$array = explode('|',$var);
foreach($array as $values) {
$arr = explode(",",$values);
if(!empty($arr) && $arr[0] == $personid){
$id = $arr[0];
$name = $arr[1];
$height = $arr[2];
break;
}
}
echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height;
?>
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
I've got a very minor problem but it's one I'd like to work out, so I'm looking for suggestions.
I'm using the following PHP code to echo the data from an array.
$array = array();
$rsa = $wpdb->get_results("SELECT * from wp_letter ORDER BY l_name ASC");
foreach($rsa as $rrr)
{
array_push($array,$rrr->l_name);
}
$temp = 0;
foreach($array as $as)
{
$temp = 0;
$query = $wpdb->get_results("SELECT * FROM wp_term_taxonomy AS tx, wp_terms AS trm WHERE taxonomy = 'category' AND trm.term_id = tx.term_id AND name like '".$as."_%' ORDER BY name ASC");
foreach($query as $row1)
{
if($temp == 0)
{
echo '<h4>'. $as.'</h4>';
$temp = 1;
}
?>
<a class="anchor" href="<?php echo esc_url(get_category_link($row1->term_id)); ?>"><?php echo $row1->name;?></a><br/>
<?php }
} ?>
Just add the LIMIT 3 into your Query, e.g.
SELECT * from wp_letter LIMIT 3 ORDER BY l_name ASC;
You could either use some crap like (for example):
$query = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$results = ['1col' => [], '2col' => [], '3col' => []];
foreach($query as $key => $result) {
if (($key+1) % 2 === 0 && !(($key + 1) % 3 === 0)) {
$results['2col'][] = $result;
} elseif (($key+1) % 3 === 0) {
$results['3col'][] = $result;
} else {
$results['1col'][] = $result;
}
}
OR just smth like this:
$results = array_chunk($query, ceil(count($query)/3));
Links:
array_chunk
ceil
I sorted a list alphabetically and data from database mysql.To read the data i am using foreach loop.Now,I want when first letter (a->b->c) will change a seperator will be add after 'A' character list and so on.
Code:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
echo $val['name']."<br>"; echo "<hr></hr>";
}
Thanks in advance
<?php
$first = '';
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
$first = substr($val['name'], 0, 1);
if ($first != $prev){
echo '<h1>'.$first.'</h1>';
}
echo $val['name']."<br>";
$prev = $first;
}
Try this:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
$lastChar = "?"; //initialization
foreach($result as $val){
if($lastChar != $val['name'][0]){
echo $val['name'][0].'<BR>'; //separator
}
echo $val['name']."<br>"; echo "<hr></hr>";
$lastChar = $val['name'][0]; //update
}
Try this (untested code) :
$firstLetter = 'A';
foreach( $result as $val ) {
$ch = substr( $val['name'],1,1);
if( $ch != $firstLetter ) {
echo "<hr>";
$firstLetter = $ch;
}
echo $val['name']."<br>";
}
$char = 'a';
foreach($result as $val) {
$newChar = substr($val['name'],0,1);
if ($newChar != $char) {
$char = $newChar;
echo "seperator for new character";
}
//do your other stuff
}
Is this what you were wanting to do?
I am trying to build an array of cart items that has a mix of a la carte items and package deals. I want to pull the products from the packages and enter the products into my order table. Below is what I have. It pulls the data, but will only add the last record of the inner array (package products) to the outer array. The a la carte items are fine.
$sql = "SELECT id, item_id, package
FROM cart WHERE user_id = $userId";
$result = dbQuery($sql);
$arrCartContent = array();
while ($row = dbFetchAssoc($result)) {
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
}
$arrCartContent[] = $row;
}
if(!empty($arrCartContent)) {
foreach ($arrCartContent as $cartData) {
$product_id = $cartData['product_id'];
$description = $cartData['description'];
$sqlInsert = "INSERT INTO shop_order_x_product
(order_id, product_id, description)
VALUES
($orderId, $product_id, '$description')";
$resultInsert = dbQuery($sqlInsert) or die('Cannot add order products: ' . mysql_error());
}
}
You mixed it up a bit, your general approach is fine, maybe streamlining it a bit will make this a breeze and prevent you from overwriting the $row variable inside the loop:
$arrCartContent = array();
while ($row = dbFetchAssoc($result))
{
if ($row['package'] == 1)
{
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
foreach($arrProductData as $productData)
{
$new = array();
$new['product_id'] = $productData['product_id'];
$new['description'] = $productData['description'];
$arrCartContent[] = $new;
}
}
else
{
$itemDetails = fetchProductDetails($row['item_id']);
$new = array();
$new['product_id'] = $row['item_id'];
$new['description'] = $itemDetails['name'];
$arrCartContent[] = $new;
}
}
You're overwriting the $row array elements with each iteration. Try...
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
$arrCartContent[] = $row;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
$arrCartContent[] = $row;
}