How to remove matched value in array - php

I am looping thru two Arrays. $wooProducts and $data. Both arrays look the same and contain WooCommerce products.
My goal is to loop thru $wooProducts and remove the matched product from $data.
Everything work except the unset() part. Any idea how I can make it work? I tried this as well: unset($data[$matchedProduct]);
// Find function
function find($array, $key) {
foreach ($array as $product) {
if ($product["Name"] == $key) {
return $product;
}
}
}
$updateProducts = [];
// Check if product already exist
foreach ($wooProducts as $wooProduct) {
$matchedProduct = find($data, $wooProduct->post_title);
if ($matchedProduct) {
array_push($updateProducts, $matchedProduct);
unset($data[$wooProduct]); // <---- Not working
}
}

You can use array_search() to find the index and then you can use unset.
array_search($wooProduct->post_title, $data);

Related

how to add array or row to array while foreach looping laravel 5.8

I need to get all products for category and sub categories when click on parent category
so i make loop or recursive loop to get all id for category and subcategory to search for its products
public function tree($category, $cats = array())
{
$items = category_model::select('id')->where('parent_id', $category)->get();
foreach ($items as $key=>$value)
{
//$cats = $value;
$cats = Arr::add($cats, 'id', $value);
self::tree($value, $cats);
}
return $cats;
}
public function allproduct(Request $request)
{
return self::tree($request->id);
}
I have tried this code but looping with our result
I need to add this all id to make search for products through this array
You can improve your own code and make it work by taking all the category ids at once, instead of making a for each loop there.
Also, you are missing a terminating condition which is a must when using recursive functions.
Also, you don't need to process the same ids again and again if they have already been processed.
Taking all those points in mind, do something like this:
public function tree($cats, $alreadyProcessedCats = [])
{
if (empty($cats)) {
return [];
}
$newCatIds = [];
foreach ($cats as $catId) {
//do not process it if it was alreadt processed
if (in_array($catId, $alreadyProcessedCats)) {
continue;
}
//fetch all the categories id where parent id is one of the id which is present in the $cats
$items = category_model::where('parent_id', $category)->pluck('id');
if (empty($items)) {
continue;
}
$items = $items->toArray();
$newCatIds = array_merge($newCatIds, $items);
}
//terminal condition
if (empty($newCatIds)) {
return $cats;
}
$newCats = array_merge($cats, $newCatIds);
return self::tree($newCats, $cats);
}
public function allproduct(Request $request)
{
$allCategoriesIds = [$request->id];
$allCategoriesIds = self::tree($allCategoriesIds);
}
Fix your foreach loop.
foreach ($items as $key=$value)
should be
foreach ($items as $key => $value)
I can't comment on that static Arr function (a Laravel thing I guess? due to the misuse of statics everywhere?)

Replacing an item in an object?

I'm looping through an object:
foreach ($data as $asset) {
$asset->test = 'test';
}
test exists in $data and is set to something else, I wish to replace it with 'test'.
The above fails to work. Where am I going wrong?
You should use referenced loop with & like foreach ($data as &$asset)
foreach ($data as &$asset)
{
$asset->test = 'test';
}
Referenced loop will have an effect to $data, otherwise only current $asset object changes.
You can think about using a function that already exists, like array_walk that would execute your function.
function test_exists(&$asset) {
$asset->test = "test";
}
array_walk($data, "test_exists");

php foreach iteration over object property array not incrementing the value

Please help! I have been staring at this for too long. I have a property of an object that is an array of objects. I want to pass in an object to a method of the parent object and search through that array property for a match, and if one is found return the index. Otherwise, I need it to return -1. For some reason, it is not iterating. If I echo out what should be the $order->product property (where the index is pointing during the loop), it is unchanging. I have dumped the array and I know it contains different values. I can show you a big var dump, but I figured I would first ask if there is a simple error or something else that is obvious to you that I have missed.
public function getItemIndex($prod) {
if (isset($this->orders)){
foreach($this->orders as $key => $order) {
if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
return $key;
} else { return -1; }
}
}
else {
return -1;
}
}
If anyone has any ideas, I am open to discuss and post more information as needed. Thank you for your time.
You are ALWAYS returning a value on the first iteration, either the $key or -1. Try removing the else statement that you currently have. This will allow you to fully iterate over the entire array.
public function getItemIndex($prod) {
if (isset($this->orders)){
foreach($this->orders as $key => $order) {
if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
return $key;
}
}
}
return -1;
}
This will ONLY return -1 once it has iterated over everything and found nothing to match. It will still return $key if it finds a match.

PHP - Apply operations to descendant arrays regardless of parent arrays

In a multidimensional array, I'm trying to select all descendant arrays with a certain key, no matter what their parent arrays are. I know the following syntax doesn't work, but hopefully it will help illustrate what I'm trying to accomplish:
<?php
foreach ($array[*][*]['descendant'] as $descendent) {
// do stuff
}
?>
Similarly, I need to figure out whether sibling arrays do not contain this array key. Something like this (again, I know the syntax is horribly wrong):
<?php
foreach ($array[*][*]['descendant'] < 1 as $descendent) {
// do stuff
}
?>
If there are always 3-dimensional array, you can use nested loop:
foreach($array as $lv1) {
foreach($lv1 as $lv2) {
foreach($lv2['descendant'] as $descendent) {
// do stuff
}
}
}
If you want to support unlimited number of dimension, you can use this ugly code
function drill($arr) {
if (isset($arr) && is_array($arr)) {
foreach($arr as $key => $value) {
if ($key == 'descendant') {
foreach($value as $descendent) {
// do stuff here
}
} else {
drill($value);
}
}
}
}
drill($array);

PHP: How do i remove an element from a multidemision array?

I have this code to add new elements to a multidimension array:
$this->shopcart[] = array(productID => $productID, items => $items);
So how do i remove an element from this array? I tried this code, but its not working:
public function RemoveItem($item)
{
foreach($this->shopcart as $key)
{
if($key['productID'] == $item)
{
unset($this->shopcart[$key]);
}
}
}
I get this error:
Warning: Illegal offset type in unset in C:\xampplite\htdocs\katrinelund\classes\TillRepository.php on line 50
public function RemoveItem($item)
{
foreach($this->shopcart as $i => $key)
{
if($key['productID'] == $item)
{
unset($this->shopcart[$i]);
break;
}
}
}
That should do the trick.
Update
There is also an alternative way:
if ( false !== $key = array_search($item, $this->shopcart) )
{
unset($this->shopcart[$key];
}
You're not enumerating over indices, but values there, to unset an array index, you have to unset it by index, not by value.
Also, If your array index is actually the productID you can eliminate the loop altogether:
public function RemoveItem($productID)
{
if (isset($this->shopcart[$productID]))
{
unset($this->shopcart[$productID]);
}
}
Your example doesn't show how you are adding items to $this->shopcart, but this may or may not be an option for you depending on the needs of your project. (i.e. not if you need to have seperate instances of the same productid in the cart).

Categories