Accessing Array Data in Object - php

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

Related

Output the imtId value

Please tell me how to output the imtId value, the array is not complete, I will not output further, but the meaning should be clear.Thank you in advance
Array
(
[id] => mavrin-wildberries-1635334576193516728
[jsonrpc] => 2.0
[result] => stdClass Object
(
[cards] => Array
(
[0] => stdClass Object
(
[id] => d3c33a3f-f5b3-5647-8e7a-ad50d27d4417
[imtId] => 30306963
[userId] => 0
[supplierId] => e9b901b9-b663-5648-97b8-6313d0e245ba
[imtSupplierId] => 0
I tried:
echo ['result']['cards'][0]['nmId']
A few things:
You need to echo an actual variable, not just a series of indexes.
The item inside "result" is an object, not an array
So is the item within the "0" index.
There is no such index as "nmld" - you said you wanted "imtId" instead, so I don't know why you didn't use that?
Therefore, if this data is contained in a variable called $arr then something like
echo $arr["result"]->cards[0]->imtId;

Looping though arrays dealing with null values

I have an array myArray
Array ([0] =>(
Number => 02348
Food => Array (
[0] => orange
[1] => apple
[2] => plum )
State => Array (
[0] => california
[1] => texas
[2] => arizona )
Status => good )
[1] =>(
Number => 34
Food => Array (
[0] => grape
[1] => bannana
[2] => tomato )
Status => rotten )
[2] =>(
Number => 007
Food => Array (
[0] => oranges
[1] => apples
[2] => plums )
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
Status => good )
I am looping though my array and then grabbing the fields i need.
for($index=0; $index < count($myArray); $index++){
$food = array_values(array_filter($myArray[$index]["Food"]));
$states = array_values(array_filter($myArray[$index]["State"]));
For the $states line i get an error of
Notice: Undefined index: State
Warning: array_filter() expects parameter 1 to be array, null given
As you can see in my array State may not always be present, is there a way to get around this. Also there is a large amount of data is being pulled dynamically and it would be difficult to change the structure of the array.
How can i loop though my array ignoring nulls but still keeping the place of State. For example
State => Array (
[0] => ohio
[1] => utah
[2] => vermont )
would still be mapped to the [2], and not shifted to [1].
$states = array_values(array_filter($myArray[$index]["State"]));
Using the above example from your code, the array_filter function expects an array so you will need to check that the variable $myArray[$index]["State"] passed to the function is both set and also an array. This will remove the notices and warnings.
You can test for an array using the is_array() function and test if a variable is set using the isset() function.
In this example, an intermediate variable $states_array is set using data from your array. It checks if the original variable is valid, otherwise, it is set to an empty array. This is then passed into the array_filter function.
$states_array = (isset($myArray[$index]["State"]) && is_array($myArray[$index]["State"])) ? $myArray[$index]["State"] : array() ;
$states = array_values(array_filter($states_array));
You may also be interested to know that PHP 7 provides a null coalesce operator which may be helpful when handling variables that may or may not be set.
See:
http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

How can I access ID array of its value

I am analyzing someone's else code where I found during debugging the type and values of a class variable during run time:
echo print_r($this->_out);
Array
(
[id] => -1
[fieldErrors] => Array
(
)
[error] =>
[data] => Array
(
)
[row] => Array
(
[DT_RowId] => row_177
[id] => 177
[last_name] => sdfdsf
[first_name] => dsf
[homeaddr] => sdfdsfsdfdsfdsfdsfdsf
[email] => s#jj.com
[officeaddr] => wwwwwwwwwwwwwwwwwwwwwwww
[mobile] => 11111111
[age] => 11
[chargeamt] => 11
[start_date] => 11/11/2011
)
)
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am a newbie in PHP and would like to know how I can access [id] => 177 value i.e. value 177.
I tried out many ways
$this->_out['row']['id'][0]
It gave me below result:
1{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
while
I tried out many ways
$this->_out['row']['id']
It gave me below result:
177{"row":{"DT_RowId":"row_177","id":"177","last_name":"sssss","first_name":"ss","homeaddr":"sssssssssssssssssssss","email":"ss#ww.com","officeaddr":"sssssssssssssssssssssssssssss","mobile":"11111111","age":"11","chargeamt":"11","start_date":"01\/01\/2001"}}
and others but its just not giving me the expected.
How can I access the value as desired?
You are doing it right. $this->_out['row']['id'] will return desired result (check why you get also JSON string that is not part of print_t($this->_out).
This will return result 177:
$this->_out['row']['id'];
And since in PHP you can access string characters as array, this will returns first character in string (that is 1):
$this->_out['row']['id'][0];
And this will throw error as there is no such index (string length is 3, so last index is 2):
$this->_out['row']['id'][5];
The print_r result is an array with more arrays on it. So first of all you must find the index of the main array which index represents the sub-array with the value you are looking for. And then you must use this index to access the sub array values.

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.

Change value in first of two arrays (multidimensional) PHP

I want to change the number in the first array in a multidimensional array. I have a code that outputs the value to an array and there is no chance for it to start counting from one - in my code. So my idea is to change the value starting from one - after it has been declared. My array look like this:
Array
(
[53] => Array
(
[name] => Volkswagen
[regularePrice] => 2139.00
)
[54] => Array
(
[name] => BMW
[regularePrice] => 2219.00
)
[55] => Array
(
[name] => Chrysler
[regularePrice] => 2399.00
)
)
I want - through a while or for - go through the array and change the values 53 to 1, 54 to 2, 55 to 3 and so on depending on how long the array is.
How do I accomplish this?
The answer is:
array_values($arr);
did you try:
$array = array_values($array);

Categories