Ok So I'm using wordpress and PHP.
Basicly I get a chosen category from a dropdown menu. I then find it's parents.
But then comes the part where I seem to fail. The output of $parents is a string with the names instead of the ID's.
So I try to get each word from the string into an array.
And loop through them and convert them to their ID number.
I commented out where it doesnt seem to work. What am I doing wrong?
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by (this seems to output a string)
$parents = get_category_parents( $selected_val, true, ',' );
/*
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++) {
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
*/
//the array should look something like this.
//$categoriesArray = ["21","44"];
try this,
function get_level($cat, $level = 0)
{
if ($cat->category_parent == 0) {
return $level;
} else {
$level++;
$cat = get_category($cat->category_parent);
return get_level($cat, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$your_cat = get_category($cat);
echo get_level($your_cat);
}
It had to do with the name of the category. I needed to use the slug instead of the name.
Here is my code that works. I can now make a new post and give it a category with their parents included!
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by ,
$parents = get_category_parents( $selected_val, true, ',',false);
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++)
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
Related
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('user_cart' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['user_cart'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('user_cart' => $course->id));
}
}
$data['user_cart'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
Current Output
[{"user_cart":86},{"user_cart":84}]
Expected Output
[84,86]
Now I am having the current Output but I want expected one. I tried by removing the json_encode but it didn't work for me.
You can use array_column() like so
$new_array = array_column($cart_array, 'user_cart');
When you are creating the output array, you are using...
array_push($cart_array, array('user_cart' => $course->id));
which is why you get the sub arrays with the keys. If instead you just add the $course->id values, then this should build the output in the first place rather than having to process it further...
$cart_array[] = $course->id;
You would also need to change the line
if ($cart_for_eacch_course['user_cart'] == $course->id) {
to
if ($cart_for_eacch_course == $course->id) {
as you no longer have the sub index. You could change this part of the code to use in_array() instead which would also be shorter.
I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);
I have a data array that totals all the items in the cart for all the products as one number.
I've been trying to figure out a way to get a data array count() all the different totals of all the different items in the cart and have them presented in my data layer comma separated. I hope that makes sense.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// # Products
$data['u1'] = count($items);
The above will return:
dataLayer = [{"visitorLoginState":"Logged out","visitorType":"NOT LOGGED IN","visitorLifetimeValue":0,"visitorExistingCustomer":"No","u1":2,"u2":["889623392590","889623135517"]
It shows a total of 2 products for the U1 variable and the two sku's for the u2 variable in the data array.
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
Would i use array_sumor some type of multi-dimensional array to acquire my needs?
If i have multiple products for the first sku i want it to seperate
the quantities. ie.. "u1":1,1,3
It is not exactly clear to me is the relationship between sku and product and which variables in your array refer to which. I make the following presumptions:
1) A product is equivalent to one $items element
2) A sku is a unique $itemIds[] value
I use the array key as a simple way to keep track for each unique sku and the value to keep track of the product count for the sku.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
// My addition (UPDATE: fixed to the correct variable name)
$uniqueItemIds = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
// *******************************
// My addition / changes
$sku = $item->getSku();
$itemIds[] = $sku; // I don't use this but keep $itemIds for compatibility
// use the array key to track counts for each sku
if (!isset($uniqueItemIds[$sku])){
$uniqueItemIds[$sku] = 1; // UPDATE: fixed to start at 1 not 0
} else {
$uniqueItemIds[$sku]++;
}
// *******************************
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// show # Products
// "u1":1,1,3 NOTE: this should be a string => "u1":"1,1,3"
$data['u1'] = "";
foreach ($uniqueItemIds as $key => $val)
// show unique skus in u2
$data['u2'][] = $key;
// show counts for each sku in u1
if (strlen($data['u1'] == 0)){
$data['u1'] = (string)$value;
} else {
$data['u1'] .= ("," . $value);
}
}
How about something like...
if ($order->getId()) {
.....
.....
.....
/** #var Mage_Sales_Model_Quote_Item $item */
$sku_based_array = array();
foreach ($items as $item) {
......
......
......
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
if (isset($sku_based_array[$item->getSku()])) {
$sku_based_array[$item->getSku()] = $sku_based_array[$item->getSku()]++;
} else {
$sku_based_array[$item->getSku()] = 1;
}
}
// # Products
$data['u1'] = array_values($sku_based_array);
Looking at the code it looks like it will only every return one product as the $parent variable is overwritten to get a first item. I have added a new variable named $itemProductCounts this will be returned to the output $data array as itemProductCounts I suspect this will always equal one.
<?php
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
$itemProductCounts = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
$itemProductCounts[$item->getSku()] = count($parent);
}
// # Products
$data['u1'] = count($items);
$data['itemProductCounts'] = $itemProductCounts;
With that all being said, the code above should get you close to what you need, you should replace the line $itemProductCounts[$item->getSku()] = count($parent); with the correct array with the product counts for that SKU.
Part of the issue with your data here is that everything in an $item is hidden behind an accessor. Rather than creating multitudes of arrays, I would suggest either creating a new object to house the information, or just modifying the $item directly.
Messing with the object directly has the risk of you accidentally using a variable name that exists in a protected or private scope though, so probably best to use your own, like so.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
// only need one array, no need for all data points to have their own
$myItems = [];
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// basic shell
$myItem = [];
// get $options and $parent
// ...
// build your own data object
$myItem['sku'] = $item->getSku();
$myItem['name'] = $parent->getName();
$myItem['price'] = $item->getBasePrice() ?: 0;
$myItem['margin'] = $this->_calculateMargin($parent, null, $item);
$myItem['type'] = $parent->getAttributeText('season');
$myItem['gender'] = $parent->getAttributeText('gender');
$myItem['sport'] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$myItem['categoryId'] = $categories['id'];
$myItem['categoryName'] = $categories['name'];
$myItems[] = $myItem;
}
// At this point, $myItems is manipulable by all the array_* functions
// number of items e.g. 3
$data['u1'] = count($myItems);
// array of skus e.g. ["889623392590","889623392590","889623135517"]
// note: can use objects for $myItem if on PHP 7
// if you like -> notation better (in the loop)
$skus = array_column($myItems, 'sku');
// array of skus with counts e.g. ["889623392590" => 2, "889623135517" => 1]
$skus_with_counts = array_count_values($skus);
// just the counts (assuming indexes on other arrays must match) e.g. [2, 1]
// note: might be useful if you want to keep the counts as an array in dataLayer
$sku_counts = array_values($skus_with_counts);
// if you want this as a comma-separated list for u1, e.g. "2,1"
// note: will also work if you implode $skus_with_counts
$data['u1'] = implode(',', $sku_counts);
// get a list of unique SKUs (both will work), e.g. ["889623392590","889623135517"]
$data['u2'] = array_unique($skus);
$data['u2'] = array_keys($skus_with_counts);
}
Most of these kinds of PHP functions will work on your other data types as well if you want to do counting and clustering, and as you point out, you can run sum operations over them as well if you wish.
PHP array manipulation references: array_column, array_count_values, array_values, implode, array_unique, array_keys.
As a sidebar, Mage_Sales_Model_Quote_Item does have a getParentItemId() method available and a getQtyOptions method, which returns both the quantity and the product model.
I think you are mixing things.
In a simple sistem you should have:
Order has an array of OrderedItems
Each OrderedItem stores ProductObject and OrderedQuantity
And the ProductObject contains all product data.
So in your example instead of counting SKUs you must have $item->quantity field and you should work with that when you add/delete/edit order contents.
I have this array
$products[0]['productid'] = 5;
$products[0]['name'] = "apples";
$products[0]['seller'] = 1;
$products[1]['productid'] = 15;
$products[1]['name'] = "orange";
$products[1]['seller'] = 1;
$products[2]['productid'] = 5;
$products[2]['name'] = "apples";
$products[2]['seller'] = 2;
// .... more 5000 products
this array is filled by the client with ajax. I need to make a restriction that $products array don't have the same productid in any of it's other members. as in the invalid data example above 5
What I do to get that done is by doing this
$onlyids = array();
for($x=0; $x < count($products); $x++){
$onlyids[]=$products[$x]['productid'];//get only productid in an array
}
//remove duplicate members
$onlyids2= array_unique($onlyids);
//check if there were duplicates
if(count($onlyids) != count($onlyids2)){
//same id found, reject client inputs
}
did I do it correct ? or there is a better performing way. because my way is obviously consume more time on big arrays?
Probably the most performant way is to store found product ids as array keys while you iterate the data:
$productIds = [];
foreach ($products as $product) {
if (isset($productIds[$product['productid']])) {
throw new Exception('Duplicate product id ' . $product['productid']);
}
$productIds[$product['productid']] = true;
}
echo 'All good';
More obscure and inefficient, but a one-liner:
if (max(array_count_values(array_column($products, 'productid'))) > 1) {
throw new Exception('Invalid input');
}
I am trying to build a loop to show different location names based on the page ID. I am trying a for loop, but not sure how to get the 2 results, I tried a foreach, but still got lost.
$location = array( "Frisco" => "1507", "McKinney" => "1509");
$count = count($location);
for($i = 0; $i < $count; $i++){
if(is_page($location[$i])) {
$location = "";
}
}
Need results =
// Add Shortcode
function dynamicLocation(){
if(is_page('1')){
$location = "McKinney";
}
else if(is_page()){
$location....
}
}
Forget for, use foreach:
foreach ($location as $key=>$value){
//here $key is the location and $value is the ID
//e.g. $key="Frisco", $value="1507"
}