Adding element to a multidimensional array in PHP - 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
)

Related

Fast searching approach in multidimensional array

The above searching I want with minimum number of code and with best serach performance.
I want to generate an array from this above array by putting logic like:
ALL "EMA" key values of array should not be allowed to match with "JACKSON" key values. Similarly all "JACKSON" key values of the same array are not allowed to fall in any value of "EMA" key. So the resulting array would be like shown below:
Array
(
[0] => Array
(
[EMA] => A
[JACKSON] => B
)
[2] => Array
(
[EMA] => D
[JACKSON] => E
)
)
I want to know the best approach with lesser code to achieve this. The method I have used seems so lengthy. I want a shorter and robust approach.
I think this might be a solution:
$emas = array();
$jacksons = array();
foreach($array as $element){
$emas[] = $element['EMA'];
$jacksons[] = $element['JACKSON'];
}
//array_intersect returns the common values in the arrays as an array
if(!empty(array_intersect($emas, $jacksons))){
echo 'array is invalid!';
}

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

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

php loop through array with duplicate index

I am trying to loop through an array with duplicate indexes. But it only prints 3 times not all of them. I want to print all values in the array is that possible?
Here is my PHP code:
$data['Video'][0]['name']='a';
$data['Video'][1]['name']='b';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='d';
$data['Video'][3]['name']='e';
foreach ($data['Video'] as $video) {
print_r($video);
}
And here is the output of that code:
Array
(
[name] => a
)
Array
(
[name] => c
)
Array
(
[name] => e
)
Well, the duplicate indexes negate each other. So this is expected behavior. So when you set this in your code:
$data['Video'][0]['name']='a';
$data['Video'][1]['name']='b';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='d';
$data['Video'][3]['name']='e';
It really just means this:
$data['Video'][0]['name']='a';
$data['Video'][1]['name']='c';
$data['Video'][3]['name']='e';
The newer data assigned to the keys 1 and 3 overwrite what was previously there.
Please avoid duplicate entry of keys otherwise try this,
$data['Video'][]['name']='a';
$data['Video'][]['name']='b';
$data['Video'][]['name']='c';
$data['Video'][]['name']='d';
$data['Video'][]['name']='e';
foreach ($data['Video'] as $video) {
print_r($video);
}

Access Node Array 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.

Categories