I need to get productID(s) from an order and display this way:
[1234, 7534, 4587]
I am able to get the product IDs this way:
$incrementId = "12345";
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$items = $order->getAllItems();
$itemcount= count($items);
$meuproduto = array();
$i=0;
foreach($items as $itemId => $item) {
$meuproduto[$i]['id'] = $item->getProductId();
echo implode(", ", $meuproduto[$i]);
}
For example this order had products 2709 and 7048, so I would like to display:
[2709, 7048]
But with the code I have it's showing:
27097048
I have tried str_replace("", ", ", $meuproduto[$i]);, but I get same result. I tried different ways, but always with same result.
print_r($meuproduto[$i]);
results:
Array ( [id] => 2709 ) Array ( [id] => 7048 )
Your echoing out each product rather than the list of products, so put the echo outside of the loop.
You are also never changing $i, so it will always write to the first element of the array, you can just use [] to add an item to the end of an array...
$meuproduto = array();
foreach($items as $itemId => $item) {
$meuproduto[] = $item->getProductId();
}
echo implode(", ", $meuproduto);
You Can Use Folowing code
$meuproduto = array();
foreach($items as $itemId => $item) {
$id = $item->getProductId();
array_push($meuproduto,$id);
}
print_r($meuproduto);
Related
I have an array named $products, which contains let's say 2 different products which are also arrays:
$products[0] = array("product_name"=>"Honda", "product_id"=>001)
and
$products[1] = array("product_name"=>"Hyundai", "product_id"=>002)
I would like to go through all the products in $products and store the names of every product into a single string variable named $allProductsNames- so that when I echo this variable the result will be:
echo $allProductsNames; //will print a string: Honda, Hyundai
I guess, the the base for that code is:
foreach ($products as $key => $product)
{
/* extracting every $product['product_name']
and storing it into $allProductsNames */
}
I would appreciate Your help with the rest of it.
You can do this easily with the array_column and implode functions.
echo implode(', ', array_column($products, 'product_name'));
You can start by adding all the product_name values from $products into $allProductsNames and then use implode() to print in out.
$allProductsNames = "";
foreach($products as $product){
$allProductsNames[] = $product['product_name'];
}
echo implode(', ', $allProductsNames );
$allProductsNames = [];
foreach($products as $product)
{
foreach($product as $key=>$value)
{
if($key === 'product_name')
{
array_push($allProductsNames, $value);
}
}
}
You mean something like this?
I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.
I'm creating an Inventory system in PHP
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$sql = mysqli_query($mysqli, "SELECT * FROM booklists WHERE book_id='$item_id' LIMIT 1");
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row["book_name"];
When I echo my $_SESSION using this
print_r($_SESSION["cart_array"]);
I added 2 item in the cart with the quantity of 1 and 55
Array (
[0] => Array ( [item_id] => 37 [quantity] => 1 )
[1] => Array ( [item_id] => 32 [quantity] => 55 )
)
I wanna update all of the [quantity] values in my session. how do you think I can achieve it ?
The question isn't overly clear, as I don't know what the quantity needs updating by, but to update each quantity, you could do something like this.
foreach($_SESSION['cart_array'] as $index => $item){
// Add 1 to each quantity
$_SESSION['cart_array'][$index]['quantity']++;
}
// Or...
$increaseBy = 5;
foreach($_SESSION['cart_array'] as $index => $item){
// Increase by a fixed amount.
$_SESSION['cart_array'][$index]['quantity'] += $increaseBy;
}
// Or...
foreach($_SESSION['cart_array'] as $index => $item){
// Increase by a random number between 5 and 15.
$_SESSION['cart_array'][$index]['quantity'] += rand(5, 15);
}
// Or...
foreach($_SESSION['cart_array'] as $index => $item){
$increaseBy = $this->getQuantityIncrease($item['item_id']);
$_SESSION['cart_array'][$index]['quantity'] += $increaseBy;
}
// Or...
// By using references.
foreach($_SESSION['cart_array'] as $index => &$item){
$increaseBy = $this->getQuantityIncrease($item['item_id']);
$item['quantity'] += $increaseBy;
}
You can try something like this in your loop,
foreach ($_SESSION["cart_array"] as $key => $item) {
$_SESSION['cart_array'][$key]['quantity'] = 13; // set the qty you want
}
You can use a foreach loop to do this.
$newQuantityValue = 10;
foreach($_SESSION['cart_array'] as $key => $value){
$_SESSION[$key]['quantity'] = $newQuantityValue;
}
All we do here is assign a new value for our quantity and then use a foreach loop to iterate through the $_SESSION variable so that we can update each of your quantity fields with our new value (in this case 10).
For more information about foreach loops, check out the the PHP Docs
Pass By Reference:
You could equally change the value by passing it by reference like this:
$newQuantityValue = 10;
foreach($_SESSION['cart_array'] as $key => &$value){
$value['quantity'] = $newQuantityValue;
}
Because we are passing it by reference, there is no longer any need to reference the $_SESSION
From the docs:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
As a side note:
You could dispense with the $newQuantityValue variable all together and instead just put the number into the loop like this:
foreach($_SESSION['cart_array'] as $key => $value){
$_SESSION[$key]['quantity'] = 10;
}
I've looked on stackoverflow for the answer, but no one explains it properly.
I have a while loop that works:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
And when I print out the array:
Array ( [team_id] => 26 [team_points] => 100 )
But my foreach returns an invalid argument.
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
I've tried many different ways but nothing works.
Thanks!
Problem is in fetching data from DB. Modify your while loop like this:
info = array();
while($get_info = mysql_fetch_array($info_result)){
$temp_info = array();
$temp_info['team_id'] = $get_info['team_id'];
$temp_info['team_points'] = $get_info['team_points'];
$info[] = $temp_info;
}
Now your foreach loop should work properly.
Here is a bit more explanation, if what you've seen so far doesn't make sense. When you do this:
$info = array();
while($get_info = mysql_fetch_array($info_result)) {
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
You are overwriting $info with each iteration of the while loop. So at the end of your loop, $info will only contain the last row of your query result.
This explains the result you see:
Array ( [team_id] => 26 [team_points] => 100 )
So when you iterate this array with
foreach ($info as $info_mation ){
echo $info_mation['team_id'];
echo $info_mation['team_points'];
echo "<br/>";
}
$info_mation will contain 26, and then 100, which are indeed invalid for foreach.
You need to create a multidimensional array rather than a one-dimensional array. You can do that by modifying your while loop slightly:
while($get_info= mysql_fetch_array($info_result)) {
$info[] = $get_info;
}
Doing it this way adds a new array element to the $info array with each iteration, rather than overwriting the same two elements repeatedly.
this is your code:
info = array();
while($get_info= mysql_fetch_array($info_result)){
$info['team_id'] = $get_info['team_id'];
$info['team_points'] = $get_info['team_points'];
}
change it to this:
$info = array();
while($get_info= mysql_fetch_array($info_result)){
$info[] = array(
'team_id' => $get_info['team_id'],
'team_points' => $get_info['team_points']
);
}
so, your $info variable contains all the array from the sql result you made.
foreach($info as $inf) {
echo $inf['team_id'];
echo $inf['team_points'];
echo '<br>';
}
and we're done! :)
How can I add key value pairs to an array?
This won't work:
public function getCategorieenAsArray(){
$catList = array();
$query = "SELECT DISTINCT datasource_id, title FROM table";
if ($rs=C_DB::fetchRecordset($query)) {
while ($row=C_DB::fetchRow($rs)) {
if(!empty($row["title"])){
array_push($catList, $row["datasource_id"] ."=>". $row["title"] );
}
}
}
return($catList);
}
Because it gives me:
Array ( [0] => 1=>Categorie 1 [1] => 5=>Categorie 2 [2] => 2=>Caterorie 2 )
And I expect:
Array ( [1] =>Categorie 1 [5] => Categorie 2 )
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = 'joy#cargomar.org';
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"] is the key for where the value of $row["title"] is stored in.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge function in loop to combine the each new $new_row array.
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}