Compare array values with others values from the same array - php

What I’m trying to achieve is that, it will loop trough the array. Then it will look if the items in the array are the same on three points: product_id, the size value and the color value.
I want to create a new array where the items are listed, the only thing I don’t want is the duplicated values. I want that the duplicated values if they are the same on those three points that the quantity will be count together. Like if I have 3 items same product id same size and same color and both of the three I ordered 3 items in my new array this is just standing 1 time and the quantity will be 9. So there will be no duplicated values in my new array.
Current loop
foreach($orders as $key => $order){
foreach($order['orderProducts'] as $key => $value){
echo '<pre>';
print_r($value['attributes']);
echo '</pre>';
}
}
results in the the following array
Array
(
[id] => 2
[product_id] => 4
[order_id] => 2
[name] => swag3
[description] => haha
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":1,"name":"Size","value":"XS","active":1},{"id":8,"name":"Color","value":"Wit","active":1}]
)
Array
(
[id] => 3
[product_id] => 3
[order_id] => 3
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Array
(
[id] => 4
[product_id] => 3
[order_id] => 4
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 1
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Sort of what I’m looking for..
Array
(
[id] => 2
[product_id] => 4
[order_id] => 2
[name] => swag3
[description] => haha
[price] => 19.95
[proceeds] => 10.00
[quantity] => 2
[attributes] => [{"id":1,"name":"Size","value":"XS","active":1},{"id":8,"name":"Color","value":"Wit","active":1}]
)
Array
(
[id] => 3
[product_id] => 3
[order_id] => 3
[name] => swag2
[description] => lol
[price] => 19.95
[proceeds] => 10.00
[quantity] => 3
[attributes] => [{"id":2,"name":"Size","value":"S","active":1},{"id":7,"name":"Color","value":"Zwart","active":1}]
)
Solution
Note it's blade php as frontend.
Backend
$order // is the array with products
$items = [];
foreach($orders as $key => $order){
foreach($order['orderProducts'] as $op){
$i = [
'product'=> Product::findOrFail($op->product_id)->toArray(),
'attributes' =>$op->attributes,
'quantity'=>$op->quantity
];
$matchedResult = false;
$count = count($items);
for($a = 0; $a < $count; $a++){
// Items with the same product_id in the $item array
if($items[$a]['product']['id'] == $i['product']['id']){
//check if the attributes are also the same
if($items[$a]['attributes'] === $i['attributes']){
// The attributes ar ethe same so up the quantity
$items[$a]['quantity'] += $i['quantity'];
$matchedResult = true;
continue; // If its right there are no other matches
}
}
}
if($matchedResult === false){
// only push item if there is not a match.
$items[] = $i;
}
}
}
Frontend
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>quantity</th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td>{{$item['product']['name']}}
#if(count($item['attributes']) > 0) <small>
#foreach($item['attributes'] as $att)
{{$att['name']}} - {{$att['value']}}
#endforeach
</small>
#endif</td>
<td>{{$item['quantity']}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>

You can achieve your goal without using nested loops. You may use hash function of product_id, size and color parameters and use that value as a new array key like this:
$orders = // original array;
$newOrders = []; // new array
foreach($orders as $order) {
$pi = $order["product_id"]; // get product_id
$attr = json_decode($order["attributes"]); // get attributes:
$size = $attr[0]->value; // get size value
$color = $attr[1]->Color; // get color
$hash = sprintf("%s.%s.%s", $pi, $size, $color); // Calculate hash
if ($newOrders[$hash]) {
$newOrders[$hash].quantity++; // If hash is already present then just increase quantity
} else {
// Otherwise add new order
$newOrders[$hash] = [
"order" => $order,
"quantity" => 1
];
}
}

I hope this can help you:
$sortedArray = [];
foreach ($order as $array) {
$tag = getTag($array);
push_to_array($sortedArray,$array,$tag);
}
function push_to_array(&$array1,$array2,$tag)
{
isset($array1[$tag]) ? $array1[$tag]['quantity'] += $array2['quantity'] : $array1[$tag] = $array2;
}
function getTag($array)
{
$attribs = json_decode($array['attributes'],true);
foreach ($attribs as $value) {
($value['name'] =='Size' ) && $size = $value['value'];
($value['name'] =='Color') && $color= $value['value'];
}
return $array['product_id'].$size.$color;
}

Try this (untested but logic should be correct):
$orders = // original array;
$new; // new array
foreach($orders as $order) {
$pi = $order["product_id"]; // get product_id
$attr = json_decode($order["attributes"]); // get attributes:
$size = $attr[0]->value; // get size value
$color = $attr[1]->Color; // get color
$duplicate = false;
foreach($newOrders as $newOrder() { // loop through nested array
$newPi = $newOrder["product_id"];
$newAttr = json_decode($newOrder["attributes"]);
$newSize = $newAttr[0]->value;
$newValue = $newAttr[1]->Color;
// check to see if same
if(
$pi == $newPi &&
$size == $newSize &&
$color == $newColor
) {
$newOrders["quantity"]++;
$duplicate = true;
break;
}
}
if(!$duplicate) {
$new[] = $order;
}
}
Edit: Sorry, I just reread your post and saw you don't want a full solution. Sorry. But I hope this can show you that nested loops are the way to go with this. As mentioned in the comments, there is no built in function for this in PHP (AFAIK).

This is not a solution, but another approach to let you think by Object Oriented Programming
It will helps you a lot in you current and next problems
Now, you have a business case, that it must be resolved in your business layer
I can assist you if you want
<?php
class Attribute {
private $_id;
private $_name;
private $_value;
private $_active;
// TODO implement getter and setter
// lTODO implement constructor
}
class Product {
private $_id;
private $_productId;
// ... order_id, name, ...
private $_attribute_a = array(); // it will be an array of attribute's object
// TODO implement getter and setter
// TODO implement constructor
private function getAttributeByName($name) {
// loop through attribute array object and return the right attribute
// foreach ($this->_attribute_a as $attr) {
// if ($attr->name === $name) return $attr;
// }
}
public function equals($o) {
if (!is_a($o, 'Product')) return FALSE;
if ($this == $o) return TRUE ;
if ($this->_productId === $o->_productId) {
$attr1 = $this->getAttributeByName('Size');
$attr2 = $this->getAttributeByName('Size');
if ($attr1->getValue() !== $attr2->getValue()) return FALSE;
$attr1 = $this->getAttributeByName('Color');
$attr2 = $this->getAttributeByName('Color');
if ($attr1->getValue() !== $attr2->getValue()) return FALSE;
return TRUE;
}
return FALSE;
}
}
Now, you can compare easily 2 Products Object, and later, updating equals() will not affect your code

You have some grate answers from other users.
However i would like to post this for Googlers or other users in the planning stage and for your own knowledge.
With your example your using a shopping basket. You should never have duplicate items in the array you should be using a Quantity measure on the item and before adding to your array you check the array if the matching item is there increase the quantity.
as your current way your code is processing though the array after for no good reason if i was to add 20 of the same item your current system would have an array of 20 to loop though every time i opened the basket.
This other method will also provide you will support for people to add multiple quantities of items at once, also on your basket page edit the quantities

Please note the assumptions below the code
function combineDuplicates($orders) {
$indexArray = array();
$uniqueArray = array();
foreach($orders as $value) {
$productID = $value['product_id'];
$attributes = $value['attributes'];
foreach($attributes as $attribute) {
switch($attribute['name']) {
case 'Size' : $size = $attribute['value'];
break;
case 'Color': $color = $attribute['value'];
break;
default : break;
}
}
if (!isset($indexArray[$productID][$size][$color])) {
$indexArray[$productID][$size][$color]['count'] = 0;
$uniqueArray[] = $value;
}
$indexArray[$productID][$size][$color]['count']++;
}
$orders = array();
foreach($uniqueArray as $key => $value) {
$productID = $value['product_id'];
$attributes = $value['attributes'];
foreach($attributes as $attribute) {
switch($attribute['name']) {
case 'Size' : $size = $attribute['value'];
break;
case 'Color': $color = $attribute['value'];
break;
default : break;
}
}
$uniqueArray[$key]['quantity'] = $indexArray[$productID][$size][$color]['count'];
}
return $uniqueArray;
}
Assumptions :
'attributes' is converted to associative array
product_id, Color & Size values are non-empty in each element

Related

PHP: how to update data in an array which is inside an array

Following is my PHP code:
while($row = $resp->fetch_assoc())
{
$itemArray = array(
array(
'name' => $row["product_name"],
'id' => $row["id"],
'image' => $row['images'],
'discount' => $row["discount"],
'quantity' => $min_quantity,
'price' => $row["price"]
)
);
}
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itemArray, $_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$item]["quantity"] = $min_quantity;
break;
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
After executing this code i am getting a response like this:
Array
(
[0] => Array
(
[name] => Girls Designer Dress
[id] => 4
[image] => s:146:"2017/march/meetfashion01-04-2017_12-19-07_am.jpg,2017/march/meetfashion01-04-2017_12-19-08_am
.jpg,2017/march/meetfashion01-04-2017_12-19-09_am.jpg";
[discount] => 10
[quantity] => 1
[price] => 1200
)
)
What I am trying to acheive is if user adds the same product in cart whose data we have got in response then instead of creating once more array and merging it one after another i want to just update the quantity of the same product from 1 to 2.
I am stuck in this part of code
foreach($_SESSION["cart_item"] as $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$item]["quantity"] = $min_quantity;
break;
}
I have tried it many times that if same product is encountered then increment the quantity by 1 for the same product and don't create one more array.
Can anyone help with this logic and code?
is $_SESSION["cart-item"] a single Array like?
Array
(
[name] => Girls Designer Dress
[id] => 4
[image] => s:146:"2017/march/meetfashion01-04-2017_12-19-07_am.jpg,2017/march/meetfashion01-04-2017_12-19-08_am
.jpg,2017/march/meetfashion01-04-2017_12-19-09_am.jpg";
[discount] => 10
[quantity] => 1
[price] => 1200
)
If so then don't call a foreach instead just check directly if that cart-item is in the $itemArray using array_search().
(The function search in a array and if needle is found return its index else return false).
$cartItemPosition = array_search($_SESSION['cart-item'], $itemArray);
if($cartItemPosition == false) {
// Not found in array, so create new entry
$itemArray.push($_SESSION['cart-item']);
}else {
// Found in array so edit existing entry
$itemArray[$cartItemPosition]['quantity'] = 999;
}
The below works if $itemArray has only 1 item :
Change to :
if(!empty($_SESSION["cart_item"]))
{
if(in_array($itemArray[0], $_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $index => $item)
{
if(in_array($item, $itemArray))
$_SESSION["cart_item"][$index]["quantity"] = $_SESSION["cart_item"][$index]["quantity"] + 1;
break;
}
}
else
{
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else
{
$_SESSION["cart_item"] = $itemArray;
}
Added [0] in first if statement of in_array.
Added $index in the foreach loop and used it.
Your code before never went to the if statement. If $itemArray is always containing an array inside an array (that's why we used [0]) then it should be like that.
If it is possible that $itemArray has more than 1 items then we will have to edit the answer as needed.
Also not sure, but if your fetching loop is possible to return more than one items then it's wrong becuse you will only have the last result. If you know that you will only have 1 result back then it's all good.
while($row = $resp->fetch_assoc())
{
$itemArray = array(
array(
'name' => $row["product_name"],
'id' => $row["id"],
'image' => $row['images'],
'discount' => $row["discount"],
'quantity' => $min_quantity,
'price' => $row["price"]
)
);
}

How to append value in array with keys without getting overriding

i'm getting result in a foreach loop now i want to form a new array with keys and form that array with my new data. Now when i try to assign data it gets override to the previous one as it's not getting new index. how can i achive that so far i have done that:
foreach ($result as $key) {
$pickup_location = $key->locationid;
if (isset($pickup_location)) {
$pickup_location = $this->db->get_where('locations', array('id' => $pickup_location ))->row();
if (!empty($pickup_location)) {
$supplier_dashboard['pickup_location_name'] = $pickup_location->name_en;
}
}
$dropoff_location = $key->location_dropoff;
if (isset($dropoff_location)) {
$dropoff_location = $this->db->get_where('locations', array('id' => $dropoff_location ))->row();
if (!empty($dropoff_location)) {
$supplier_dashboard['dropoff_location_name'] = $dropoff_location->name_en;
}
}
$car_make = $key->car_id;
if (isset($car_make)) {
$car_details = $this->db->get_where('chauffeur_rates', array('chauffeur_id' => $car_make))->row();
if (!empty($car_details)) {
$supplier_dashboard['car_make'] = $car_details->chauffeur_make;
}
}
}
return $supplier_dashboard;
}
and my resulting array is:
Array
(
[pickup_location_name] => Seoul Downtown
[dropoff_location_name] => Disneyland Paris
[car_make] => makecar
)
however i have atleast 7 location names and car makes instead of getting added as a new array it overrides the previous one, i should have get the result as
Array
[0](
[pickup_location_name] => Seoul Downtown
[dropoff_location_name] => Disneyland Paris
[car_make] => makecar
)
Array
[1](
[pickup_location_name] => Seoul 1
[dropoff_location_name] => Disneyland 1
[car_make] => makecar
)
Array
[2](
[pickup_location_name] => Seoul 2
[dropoff_location_name] => Disneyland 2
[car_make] => makecar
)
... upto 7
Every time you looping the key of the array is always the same that's why you are getting overide the results. You need to put a key that is unique. You can try this
$i = 0; //First key
foreach ($result as $key){
$supplier_dashboard[$i]['pickup_location_name'] = $pickup_location->name_en;
$i++; //add +1 to the key so the next element not overrides
}
You have to add $key to array in which your record get added
use
$supplier_dashboard[$key]['pickup_location_name'] = //your code
instead of
$supplier_dashboard['pickup_location_name'] = //your code
Instead of adding the items the your array, you are directly setting the value in the top most collection.
Instad of
$myobject['foo'] = $value;
You need to do (where $iteration is the current position in your loop)
$myobject[$iteration]['foo'] = $value;
Try the following :
$carItemNumber = 0;
foreach ($result as $key) {
$pickup_location = $key->locationid;
if (isset($pickup_location)) {
$pickup_location = $this->db->get_where('locations', array('id' => $pickup_location ))->row();
if (!empty($pickup_location)) {
$supplier_dashboard[$carItemNumber]['pickup_location_name'] = $pickup_location->name_en;
}
}
$dropoff_location = $key->location_dropoff;
if (isset($dropoff_location)) {
$dropoff_location = $this->db->get_where('locations', array('id' => $dropoff_location ))->row();
if (!empty($dropoff_location)) {
$supplier_dashboard[$carItemNumber]['dropoff_location_name'] = $dropoff_location->name_en;
}
}
$car_make = $key->car_id;
if (isset($car_make)) {
$car_details = $this->db->get_where('chauffeur_rates', array('chauffeur_id' => $car_make))->row();
if (!empty($car_details)) {
$supplier_dashboard[$carItemNumber]['car_make'] = $car_details->chauffeur_make;
}
}
$carItemNumber++;
}
return $supplier_dashboard;

Search nested multidimensional array

I have a function that fills an array:
foreach ($request->get('ids') as $id) {
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}
What I want to do
On each loop, I want to check if the array (so far) already has a desc entry equal to the current $schedule->getDescription() AND the same date as $schedule->getStart()->format('d.m.Y') (actually more, but let's keep it simple)
What I tried
public function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && $this->recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Source
I use it like that:
if ($this->recursive_array_search($schedule->getDescription(), $pdfArray['rows']) &&
$this->recursive_array_search($schedule->getStart()->format('d.m.Y'), $pdfArray['rows'])){
$pdfArray['ma'][$schedule->getId()]++;
}
but this is true when ANY of the start or desc are SOMEWHERE in the current array.
How would I check if desc is found and start is in the SAME $i level?
EDIT for example
Let's say I have 10 $ids to loop through. After 2 loops, the $pdfArray looks like this:
Array
(
[other] => 2
[rows] => Array
(
[0] => Array
(
[id] => 1
[date] => 13.07.2016
[dateSort] => 2016-07-13 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
[1] => Array
(
[id] => 2
[date] => 12.07.2016
[dateSort] => 2016-07-12 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
)
)
The next iteration has the following:
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST
So I want to have the info that the combination already exists in the array.
BUT
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST2
should NOT return true upon checking of it exists.
To test for a "duplicate" you can use this function:
function testPresence($pdfArray, $desc, $date) {
foreach ($pdfArray["rows"] as $row) {
if ($row["desc"] == $desc && $row["date"] == $date) return true;
}
}
Example use:
echo testPresence($pdfArray, "TEST2", "12.07.2016") ? "Found" : "Not found"; // Not found
echo testPresence($pdfArray, "TEST", "12.07.2016") ? "Found" : "Not found"; // Found
In your original loop, you can use it as follows:
foreach ($request->get('ids') as $id) {
if (testPresence($pdfArray, $schedule->getDescription(),
$schedule->getStart()->format('d.m.Y')) {
// We have a duplicate. Maybe skip this entry?:
continue;
}
$pdfArray['other']++;
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}
try this at your validation function
public function array_search($needle1, $needle2 ,$haystack) {
foreach($haystack as $singleArray){
if (in_array($needle1, $singleArray) && in_array($needle2, $singleArray))
return true;
else
continue;
}
return false;
}
and invoke your recursive_array_search like this
if ($this->array_search($schedule->getStart(), $schedule->getDescription(), $pdfArray['rows'])
continue;//Or any other kind of logic you want. At this place you know that description and date staet exist in at your array level
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
Function version:
/**
* Find matches for $item into pdfArray.
* Returns an index array, possibly empty if no matches.
* #param $item item to find
* #param $rows rows where to search
*/
function findPdfArrayMatches(array $item, array $rows) {
return array_keys(
array_filter(
$rows,
function ($entry) use ($item) {
// These are the matching criteria. More than one row may match.
return $entry['desc'] == $item['desc']
&& $entry['date'] == $item['date']
;
}
)
);
}
You could do like this, in the loop:
$item = [
'id' => $schedule->getId(),
'date' => $schedule->getStart()->format('d.m.Y'),
'dateSort' => $schedule->getStart()->format('Y-m-d H:i'),
'from' => $schedule->getStart()->format('H:i'),
'to' => $schedule->getEnd()->format('H:i'),
'desc' => $schedule->getDescription(),
];
$matches = findPdfArrayMatches($item, $pdfArray['rows']);
if (!empty($matches)) {
...do something with the matches:
foreach ($matches as $match) {
$pdfArray['rows'][$match]['Duplicate'] = true;
}
}
// Add new item
$pdfArray['rows'][$i] = $item;

How to find object in php array and delete it?

Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
foreach($parentObj AS $key=>$element){
if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
echo "Gottcha! The index is - ". $key;
}
}
$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.
use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;
$arr = array($a, $b);
$index = array_search($b, $arr);
echo $index;
// prints out 1
try this
foreach($array AS $key=>$object){
if($object['id'] == 4){
$key_in_array = $key;
}
}
// chop it from the original array
array_slice($array, $key_in_array, 1);
Another way to achieve the result is to use array_filter.
$array = array(
(object)array('id' => 5),
(object)array('id' => 4),
(object)array('id' => 3)
);
$array = array_filter($array, function($item) {
return $item->id != 4;
});
print_r($array);
Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
foreach( $items as $item ) {
if( $item->id == $id ) {
$key = key($item);
return $item;
break;
}
}
return null;
}
Usage
$item = search($items, 4, $key);
unset($items[$key]);
Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.
A funny alternative
$getIdUnset = function($id) use ($myArray)
{
foreach($myArray as $key => $obj) {
if ($obj->id == $id) {
return $key;
}
}
return false;
};
if ($unset = $getIdUnset(4)) {
unset($myArray[$unset]);
}
Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
$elementCount = count($elementData);
for ($i = 0 ; $i < $elementCount ; $i++){
if ($object == $elementData[$i]) {
return $i;
}
}
return -1;
}
You can save this function as a core function for later.
In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
[0]=> float(-0.12459619130796)
[1]=> float(-0.64018439966448)
[2]=> float(0)
}
Then use if condition to stop looping
foreach($array as $key => $val){
if($key == 0){ //the key is 0
echo $key; //find the key
echo $val; //get the value
}
}
I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
/**
* #param iterable $haystack
* #param callable $callback
* #param mixed|null &$item
* #return false|int|string
*/
function index_of($haystack, $callback, &$item = null)
{
foreach($haystack as $_key => $_item) {
if ($callback($_item, $_key) === true) {
$item = $_item;
return $_key;
}
}
return false;
}
}
foreach( $arr as $k=>&$a) {
if( $a['id'] == 4 )
unset($arr[$k]);
}

finding the first element that is needed

I have this array
Array
(
[name] => Step1 is here
[standard] => Array
(
[product_id] => 85,99
[product_name] => Step1 is here
[product_price] => 976.0000
[product_description] => :something
[product_image] => http://someurl.com/shop_pos/image/data/13D.png
)
[professional] => Array
(
[product_id] => 61
[product_name] => Step1 is here
[product_price] => 289.0000
[product_description] => somethingothere
[product_image] => http://someurl.com/shop_pos/image/data/13B.png
)
[premium] => Array
(
[product_id] => 677
[product_name] => Step1 is here
[product_price] => 289.0000
[product_description] => somethingothere
[product_image] => http://someurl.com/shop_pos/image/data/13A.png
)
)
Is there an easy of referencing in the proper order that i need. SO the order i need is standard, professional, premium.. so if one is not present can I do to the other like this
if (!isset($my_array['standard'])) {
$use_me = $my_array['standard']
}elseif(!isset($my_array['professional'])) {
$use_me = $my_array['professional']
}elseif(!isset($my_array['professional'])) {
$use_me = $my_array['premium']}
}
i have the above code that i think may work but is there a better way
That should do it:
$keys = array_slice(array_keys($my_array), 1, 1);
$use_me = $my_array[$keys[0]];
In short:
Get the array keys (name, standard, professional, premium). (array_keys)
Get the second key (bypassing name, so it returns standard or whatever the second key is). (array_slice)
Reference $my_array using that key and store it in $use_me.
I would do this:
foreach (array('standard', 'professional', 'premium') as $name) {
if (isset($my_array[$name])) {
$use_me = $my_array[$name];
break;
}
}
or a little more structured:
function selectPlan($array) {
foreach (array('standard', 'professional', 'premium') as $name) {
if (isset($array[$name])) return $array[$name];
}
}
$use_me = selectPlan($my_array);
Yes, you can do it the way you have presented in your code. However, your if statement logic is not correct. Your code should be like this:
if (isset($my_array['standard'])) {
$use_me = $my_array['standard'];
} elseif(isset($my_array['professional'])) {
$use_me = $my_array['professional'];
} elseif(isset($my_array['premium'])) {
$use_me = $my_array['premium'];
}
try with array_key_exists
foreach($input as $k=>$v) {
if (array_key_exists('standard', $k)) {
$output [$k] = $k;
}
if (array_key_exists('professional', $k)) {
$output [$k] = $k;
}
if (array_key_exists('premium', $k)) {
$output [$k] = $k;
}
}
or u can go through array-intersect-key
If I understand correctly what you want to do, and if the order of the keys is not guaranteed to be exactly like the one in the example, you can do something like:
// initialization
$use_me = 'default value';
// go through each package
foreach (array('standard', 'professional', 'premium') as $package) {
// when we find a package that does exist
if (isset($my_array[$package])) {
// mark it as found and exit the loop
$use_me = $package;
break;
}
}
This will go through all the packages and set the $use_me variable to the first found value. If no value is found, it sets it to a default value.

Categories