Nested array in php - 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.

Related

Remove first 2 php objects from array

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);

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'.

Remove values from array on foreach PHP

I have an array like this:
Array
(
[0] => Array
(
[id] => 68
[type] => onetype
[type_id] => 131
[name] => name1
)
[1] => Array
(
[id] => 32
[type] => anothertype
[type_id] => 101
[name] => name2
)
)
I need to remove some arrays from it if the users has permissions or not to see that kind of type. I am thinking on doing it with a for each, and do the needed ifs inside it to remove or let it as it.
My question is: What's the most efficent way to do this? The array will have no more than 100 records. But several users will request it and do the filtering over and over.
use this 1 simple and easy
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
Use in_array() function so that you could find the array that you would want to remove.
Then use unset() function to unset the array or variable that you would want to remove from your existing array.
On this way, you don't need to loop your array over and over.
I think you understand the basics of PHP and stripping the array.
What you could do after stripping the array store it in a session for re-use after a page-refresh or loading of a different page. That way, you only have to do it once.
See: http://www.php.net/manual/en/function.session-start.php

Can I turn an array in memory into the code representation of that array?

I'm not even entirely sure how to ask the question, but assuming I have an array in memory like this:
Array (
[0] => Array
(
[0] => Array
(
[0] => 18451
[1] => MDX
)
[1] => Array
(
[0] => 18450
[1] => NSC
)
[2] => Array
(
[0] => 18446
[1] => RL
)
)
)
Is there some existing functionality to turn it into the code version of that array? I have a # of arrays I need to do this for, nested to various degrees. So I imagine I want output something like
$arrayname[] = array(array('18451','MDX'),array('18450','NSC'),array('18446','RL'));
I can write something to do it, but I'd rather not recreate the wheel if there's an existing way to do it.
This may be all you need:
http://us.php.net/var_export
manually loop through the array recursively and create a string like how you want.
var_export could help you there i think. The other option would be looping through it manually :(

Categories