Remove first 2 php objects from array - php

I am want remove first 2 object from a PHP array, my code is as below
print_r($available_methods);
Output:
Array (
[free_shipping:5] => WC_Shipping_Rate Object ( [id] => free_shipping:5 [label] => International Free [cost] => 0.00 [taxes] => Array ( ) [method_id] => free_shipping [meta_data:WC_Shipping_Rate:private] => Array ( [Items] => Portsea Polo - 2018 × 1 ) )
[flat_rate:4] => WC_Shipping_Rate Object ( [id] => flat_rate:4 [label] => International Regular [cost] => 34 [taxes] => Array ( ) [method_id] => flat_rate [meta_data:WC_Shipping_Rate:private] => Array ( [Items] => Portsea Polo - 2018 × 1 ) )
[per_product] => WC_Shipping_Rate Object ( [id] => per_product [label] => Express shipping [cost] => 9.00 [taxes] => Array ( ) [method_id] => per_product [meta_data:WC_Shipping_Rate:private] => Array ( ) )
)
I want to remove first 2 array indexes and use only last one.

Try this
unset($available_methods["free_shipping:5"]);
unset($available_methods["flat_rate:4"]);

unset()
You could simply just unset the first 2 index values if the key doesn't change.
unset($available_methods["free_shipping:5"]);
unset($available_methods["flat_rate:4"]);
But, there are definitely other ways that may be better for your situation.
http://php.net/manual/en/function.unset.php
array_pop()
An alternative to unsetting the other variables is using array_pop.
$available_methods = [array_pop($available_methods)];
Notice that I wrapped it in square brackets [] which puts it back into an array. (The brackets are shorthand arrays)
If you don't care about it being in an array, you can just drop these symbols and it will be in a variable on it's own.
$available_methods = array_pop($available_methods);
array_pop() pops and returns the last value of the array, shortening
the array by one element.
In this form, this will overwrite the existing array completely with the data from the last index, but you could just as easily save it to a different variable so you can keep your original data in existence as well.
More information on array_pop() can be found in the php manual
It could get even easier
If it's always an exact index, and that index is always named the same, you could very simply just pull that index into it's own variable.
$available_methods = [$available_methods['per_product']]; //to keep it in an array
$available_methods = $available_methods['per_product']; //to keep just the variable
NOTE: If you are running a PHP version less than 5.4 (Which, if you are, you should definitely upgrade to a newer version), the short array syntax is not supported and will have to be replaced with array()
http://php.net/manual/en/language.types.array.php
NOTE: All of these solutions will probably perform very nearly the same, choosing between the different ones based on how long they take to perform would probably be considered micro-optimization, which in most cases does not matter very much. You should just choose the one that is the easiest for you to understand how it works, or maybe even the one you understand the least so that you can learn how it works. That is what I would do :)

I would look at using array_slice.
http://php.net/manual/en/function.array-slice.php
Something like the following:
$list = array_slice($available_methods, 2, null, true);

Related

Find if all elements in one multidimensional arrays exists in another (using a multidimensional array as a haystack)

I have been trying to use some logic to be able to see if all elements in a multidimensional array (haystack) exits in another much larger haystack. My first haystack comes from a json object in the first place, and the second one is a "dot name" string, that is also converted into an array. The logic here is that I can use a string describing what I'm looking for in the json in a simple way:
Needle:
Array
(
[key1] => Array
(
[provider] => Array
(
[id] => 1
)
)
[key2] => Array
(
[consumer] => Array
(
[id] => 5
)
[hostname] => foo
)
)
Haystack:
[0] => Array
(
[id] => 1000
[consumer] => Array
(
[id] => 5
[name] => test
[hostname] => foo
[1] => Array
(
[id] => 1200
[provider] => Array
(
[id] => 5
[name] => test
If the needle exists in the array the top key should be returned. So if we pretend all key->values below "key2" exists in array we should return key2. provider-id and consumer-id are not the same and there might be other key-values that might look the same, but has a different path. so if "hostname" would exists, but much deeper into array that is not a match.
The problem is that all examples I've come across either have:
A fixed depth on the array.
Having the needle as a string.
Is not true multidimensional.
Is there a way this can be done? recursiveiteratoriterator did come to my mind but not sure actually how to use it, based on the above.
I've also looked at various in_array/is_array/array_map/array_filter recursive examples but they are fell a bit messy and I couldn't decide if it was worth trying to build something that would allow to crawl two arrays in a good way.
My array is quite large and contains, sadly mostly items I'm not interested in. But if I can find a way that works I'm sure I can optimize that part.
Thanks for reading.

Searching complex array for and modifying a value in php

I have a complex multi-dimensional array that looks something like
[name] => Marko Polo
[description] => New application
[number] => ABCD1234
[loans] => Array
(
[0] => Array
(
[id] => 123
[application_id] => 456
[loan_fees] => Array
(
)
[loan_parts] => Array
(
[0] => Array
(
[id] => 987
[loan_id] => 123
[product_id] => 49788
[product] => Array
(
[id] => 49788
[lender] => MAC
...
I need to create an efficient way of traversing this array and, for example having a set of rules to filter/modify the data.
For example, in the array there is [lender] => MAC, I want to have something like
loans.loan_parts.product.lender.MAC = 'Macquarie'
This would be in a config of sorts such that if the data array changed, it would be simply a matter of changing that dot notation to point to the new location of the lender value.
Using this, I need to filter the lender and modify it to be Macquarie instead of Mac.
I know that a big no-no these days is using too many foreach loops and I've looked into Collections, but because the inner arrays are not named, I don't believe Collections is possible.
As I say, I'd like to avoid the situation of
foreach
foreach
if (is_array())
foreach
eeewww!
How can I execute this in the most efficient manner due to the possible large size of the array and its complexity.
You can use array_walk_recursive with callback that will change behavior according to key of array.
<?php
//can pass variable by reference to change array in function
function handleMAC(&$item, $key)
{
if($key == 'lender'){
$item['MAC'] = 'your value';
}
}
array_walk_recursive($array, 'handleMAC');
?>

Accessing Array Data in Object

I'm trying to access a piece of data in an array of arrays that (I believe) is in an object (this may not be the right term though).
When I do print_r on this: $order_total_modules->process() I get...
Array (
[0] => Array (
[code] => ot_subtotal
[title] => Sub-Total:
[text] => $49.99
[value] => 49.99
[sort_order] => 1
)
[1] => Array (
[code] => ot_total
[title] => Total:
[text] => $0.00
[value] => 0
[sort_order] => 12
)
)
If I run echo $order_total_modules->process()[1][3];, I should get "0", because that is the 3rd element of the 2nd array... right? Yet, I get an error.
Can anyone help with this?
Even though it is the third element counting from 0, the index is not 3 it is an associative array with the index value:
Available in PHP >=5.4.0:
echo $order_total_modules->process()[1]['value'];
Or PHP < 5.4.0:
$result = $order_total_modules->process();
echo $result[1]['value'];
You cannot access an associative array via an integer index(unless the index is an actial integer).
So in this case use :
[1]['code'] to access what woulde be [1][0] with a 'normal' array.
Try putting it in a var first:
$ar = $order_total_modules->process();
echo $ar[1]['value'];
The second level array is an assoc, which means that the key is not numeric, which means that you need to call the name of the key, hence the 'value'.

Nested array in php

I'm having trouble handling a nested array I get as result from an API. Print_r($result, true); returns an array looking like this (only much longer):
Array
(
[success] => 1
[return] => Array
(
[sellorders] => Array
(
[0] => Array
(
[sellprice] => 0.00000059
[quantity] => 1076.00000000
[total] => 0.00063484
)
[1] => Array
(
[sellprice] => 0.00000060
[quantity] => 927.41519000
[total] => 0.00055645
)
)
[buyorders] => Array
(
[0] => Array
(
[buyprice] => 0.00000058
[quantity] => 6535.77328102
[total] => 0.00379075
)
[1] => Array
(
[buyprice] => 0.00000057
[quantity] => 118539.39620414
[total] => 0.06756746
)
)
)
)
I need to grab the 3 values (sellprice/buyprice, quantity, total) from the first index of both arrays (sellorders and buyorders) and store them in variables ($sellprice, $sellquantity, $selltotal).
The full example php script I'm using can be found on the bottom of this page. Could anyone help me figure this out?
In php, arrays can more or less have infinite dimensions. You can go deeper within an array's dimensions by adding another set of square brackets. For example,
$array['deep']['deeper']['deepest'][0];
Assuming the indexes in the sellorders and buyorders are the same in your array, you could do
$sellprice = $result['return']['sellorders'][0]['sellprice'];
$sellquantity = $result['return']['sellorders'][0]['quantity'];
$selltotal = $result['return']['sellorders'][0]['total'];
The value should look something like this:
$sellprice = $array['return']['sellorders'][0]['sellprice']
You might want to think about how you iterate over these nested arrays in order to pick out all the values. Furthermore, if you have control over the output I might be better to use a different data structure to enable easier processing.
You can access the values of the nested arrays by adding another pair of square brackets with the appropriate index at the end:
$array['outer']['inner'];
It's up to you to transfer this knowledge to your specific array.
If you want to go thru all of those arrays... try this:
for($i=0; $i<count($array['return']['sellorders']); $i++) {
$this_array = $array['return']['sellorders'][$i];
var_dump($this_array); // it includes sellprice, quantity and total for each entity now.
}
use the same method as above for buyorders as well.

Sorting Multidimensional Array

Thought I will point out first that I have looked around on Stackoverflow and the internet already and although they are plenty of examples none of them are explained into such a way for me to understand how to convert the code to work with my array structure.
I believe I need to use one of the functions uksort or uasort but unsure on this as well.
My array looks like the following.
Array
(
[0] => Array
(
[Result] => Array
(
[id] => 260
[event_id] => 72
[year] => 2010
[york_score] => 27
[york_points] => 0.0
[lancs_score] => 51
[lancs_points] => 4.0
[winner] => L
[confirmed] => Y
[updated] => 2010-05-01 16:10:03
)
[Event] => Array
(
[id] => 72
[sport_id] => 25
[event_title] => 1st Team
[Sport] => Array
(
[id] => 25
[sport_title] => Netball
)
)
)
And where its [0] means it continues on.
I need to sort all of the arrays [0,1,2,3,...] by the sport_title key found in [Event][Sport]
Does anyone know how to create a sorting function to do this?
Some explanation of how the function is working would also be helpful if I later need to adapter/alter the code to work else where on my site.
Where $array is the name of the array which holds the array you posted in your question.
function sort_multi($item_1, $item_2)
{
// strcmp looks at two strings and, based off the characters' and their order,
// determines which one is numerically greater. When this function returns a
// negative, for example, it means the first item it's comparing is less that the
// second item (ef and eg, for example). The usort function then rearranges
// the array based off these comparisons.
return strcmp($item_1['Event']['Sport']['sport_title'], $item_2['Event']['Sport']['sport_title']);
}
usort($array, 'sort_multi');

Categories