Access Node Array PHP - php

How I can access an array node? For example, field "cantidad"?
Result:
Array (
[2] => Array (
[cantidad] => 1
[id_producto] => 2
[precio] => 875
[nombre] => Queso manchego
[imagen] => dodgers01.jpg
[btn_add_item] => Agregar al carrito
)
)
My code is:
<?php
$carritoactual = $this->carrito->get_carrito();
print_r($carritoactual);
?>

If you're asking questions this basic, I suggest you start reading up on the PHP manual - for this question, the Arrays page would be a good place to start.

Apparently your array $carritoactual contains one item with the index 2. The content of this element is itself an associative array.
You would refer to that array via its key (the index number) like this:
$carritoactual[2]
So if you want to print the content of that array:
print_r( $carritoactual[2] );
This is similar to what you did with the result of $this->carrito->get_carrito(); but it directly accesses the element with its key (2).
Now if you want to access cantidad, which is one of the elements inside $carritoactual[2]:
print_r( $carritoactual[2]['cantidad'] );
Notice that the main array has a numerical key, but the second array has string keys. In PHP you can mix numerical and string keys.
Of course you should read the manual.

This is an array rather than an object
$Variable[2]['cantidad'];
will get you the value you want.

Related

PHP using key of one array to access same key position on another array

I've looked at a number of suggestions for this, and they seem to rely on array_combine() which unfortunately is not suitable, as they arrays need to stay separate for other functions.
The arrays are set out as per
Array ( [0] => 3 [1] => 1 [2] => 3 )
Array ( [0] => 194 [1] => 0 [2] => 452 )
When I read in the first array, I get the key as $key and everything works fine.
Whenever I try and access the second array the whole script just whites out the page.
I want the code to work simliar to this ...
$a2value = $a2[$key] => $value;
echo $a2value;
Then I can do SQL lookups using $a2value
Any help would be appreciated
Here Try this
let's suppose two arrays of same number of elements
$a1=[1,2,3];
$a2=[194,0,452];
//A Simple foreach
foreach($a1 as $key=>$a1value){
$a2value=$a2[$key];
//Perform Query here
}
Remember one thing number of elements of both array should always be equal or it will cause an error
If you aren't certain about the size of both arrays then replace the line with this code
$a2value=empty($a2[$key]) ? null : $a2[$key];
Hope this works !!!

PHP -modify value of last accessed element in multidimensional associative array

I am reading a GEDCOM-formatted family tree flat file, and producing an array from the data for staging into table. If I encounter the values CONC <some value>, then, instead of adding an element, I need to append <some value> to the value of the last element that was just inserted (regardless of dimension depth).
I tried with current(...) etc but does this work for a multidimensional associative array?
please consider following element in an array:
[#N163#] => Array ( [INDI] => Array ( [TEXT] => Some data of this person) )
if the next line reads "1 CONC including his profession"
instead of adding a line as such
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person)
[INDI] => Array ( [CONC] => including his profession) )
I would like the array to look as follows:
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person including his profession) )
What I have researched thus far:
end($theArray)
to set pointer to last inserted element followed by $theArray[key($theArray)] = .... to update this element.
But I did not get this method to work for multidimensional arrays and/or it became really messy.
And:
merging two arrays using e.g. += notation,
but this only seems to overwrite a new element, not affect the last one, if keys are same
And:
examples with foreach calls, which does not help in my case.
Hope somebody can shed some light... many thanks!
When you adding $array[#N163#][INDI][TEXT] = 'smtng'; you can save position
$pos = &$array[#N163#][INDI][TEXT];
And if you need concatenate, write
$pos .= "concate line";

Adding element to a multidimensional array in PHP

I'm iterating over an array of courses, which all contain category IDs in the form of strings. I'm trying ro group them all by category using a matrix, but I'm having trouble doing that.
Here's an example of what I want:
$courses_by_code = [[2/11]=>[course1],[course2]], [[3/12]=>[course3], [course4]]
So my questions are:
How do I add an element that has a key that's already in the matrix to the array that corresponds to that key?
How do I create a new line in the matrix in case I find a new key?
I am not sure I understood 100%, but from what I understood you should do something like:
$keyThatMightExist // '2/11' for example
if(isset($courses_by_code[$keyThatMightExist])) {
$courses_by_code[$keyThatMightExist][] = $newCourseToAdd;
} else {
$courses_by_code[$keyThatMightExist] = array($newCourseToAdd);
}
Let's start with PHP's Arrays documentation:
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
Something that will be invaluable to you when working with arrays is the print_r function. var_dump is also useful. You will be able to see array structure as its stored in PHP. Here's some useful things to know with arrays.
Let's answer some questions now:
How do I add an element that has a key that's already in the matrix to the array that corresponds to that key? How do I create a new line in the matrix in case I find a new key?
$courses = []; // initialize
$courses['2/11'][] = 'course1';
$courses['2/11'][] = 'course2';
$courses['3/12'][] = 'course3';
$courses['3/12'][] = 'course4';
The empty [] you see indicates that I'm adding more elements to the key 2/11. If I wanted I could also name those keys, but I'm not going to do that. Using print_r (described above) I will now print the array out in a human-readable format. Note that with print_r you generally want to surround the output with <pre> tags, as such:
echo "<pre>";
print_r($courses);
echo "</pre>";
And here is my output:
Array
(
[2/11] => Array
(
[0] => course1
[1] => course2
)
[3/12] => Array
(
[0] => course3
[1] => course4
)
)
Here is how I can access these elements:
echo $courses['2/11'][1]; // this is course2
echo "<br>";
print_r($courses['3/12']); // this is the entire '3/12' array
Result:
course2
Array
(
[0] => course3
[1] => course4
)

how to fetch the array values in separate variables

Array
(
[0] => Array
(
[TotalPaid] => 0
[Description] => One-time:
[PayStatus] => 0
[InvoiceTotal] => 34.78
[TotalDue] => 34.78
[JobId] => 66
[DateCreated] => 20150311T02:57:10
[Id] => 66
)
[1] => Array
(
[TotalPaid] => 0
[Description] => One-time:
[PayStatus] => 0
[InvoiceTotal] => 89.06
[TotalDue] => 89.06
[JobId] => 68
[DateCreated] => 20150311T02:58:27
[Id] => 68
)
)
i have ds array as a output this output is in a single variable ie $invoices.. i want each value in a separate variable...
When you store an array as a variable you can access each value in the array by adding the name of the array key between [] brackets after the variable name. like so...
$invoices[0]['Description']
If you wanted to loop through your invoices you could do...
foreach( $invoices as $invoice ) {
$description = $invoice['Description'];
}
If you need more info try the PHP manual - http://php.net/manual/en/language.types.array.php
EDIT: As Chris has pointed out the second example is only for use inside the loop because the example foreach would simply overwrite the variable at each iteration so you would need to do something immediately after its assignment within the iteration or it will be lost. However the first method would allow access to the value just increment the numeric key. from 0 to 1 and you would have both results assigned their own variable.
Hope that helps.
Dan
You could loop over the outer array, with a nested loop to go over the inner array. Within these, you can construct a string using the array keys (e.g. 'TotalPaid0', 'Description0', ... 'TotalPaid1', 'Description1', etc.) and then use Variable variables to store the values in.
http://php.net/manual/en/language.variables.variable.php
In response to user4501586 comment.
The code you posted to me makes no sense, you want to output to specific variables when actually to out put to that form you actually just need to call the relevant $array[0]['key'], $array[1]['key']
By this i mean select the appropriate array key and replace corresponding letter variable that you have chosen with it.
As has been suggested this is not a make me some code that works site, we are hear to help but you seem to want us to do it for you.
Also suggested. PHP Documentation you really should read up on it because i feel you do not yet grasp even the basics and that is something we cant help you with here.

Store an array to an array key

I'm trying to store an array ($temp) into the $data array, where key is prices.
$data['prices'] = $temp;
However, PHP converts the array into string instead and is throwing me and error.
Notice: Array to string conversion
Is $data = array('prices' => $temp); the only solution?
edit:
I found my mistake. Yes, $data was used previously as a string that's why PHP is converting the input into string.
Problem 2, doing a print_r on $data['prices'] = $xml->result->Prices->Price, shows only 1 set of array. But I am able to retrive 2 sets of result by doing a foreach loop on $data['prices']. Why is that so?
Content of $temp http://pastebin.com/ZrmnKUPB
Let me be more clear..
The full xml object I'm trying to extract information from: http://pastebin.com/AuMJiyrw
I'm only interested in the price array (Price_strCode and Price_strDescription) and store them in $data['prices']. End result something like this:
Array(
[0] => (
[Price_strCode] => 0001
[Price_strDescription] => Gold
)
[1] => (
[Price_strCode] => 0002
[Price_strDescription] => Silver
)
)
Unless you are doing some other array to string conversion elsewhere, the array is actually being stored as another array.
$data['prices'] will be an array, which can be accessed as $data['prices']['key'].
This is not possible, I have been doing this always and it works fine. You must be doing something else somewhere which is causing your array to convert to strong. share your code here

Categories