looping through tridimensional arrays in php - php

I have an array of arrays that looks like this:
Array
(
[0] => Array
(
[id] => 39
[nume] => Ardeleanu
[prenume] => Bogdan
[crm] => Array
(
)
)
[1] => Array
(
[id] => 40
[nume] => Avram
[prenume] => Corina
[crm] => Array
(
[2014-02-27] => 2
[2014-02-28] => 1
)
)
)
Here is my code :
foreach ($newOrders as $crm) {
foreach ($crm as $angajati) {
foreach ($angajati['crm'] as $val) {
echo $val;
}
}
}
I getting the Warning:
Illegal string offset 'crm'.
What am I missing ?

Does it helps ?
foreach ($newOrders as $key=>$val) {
if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){
foreach($val["crm"] as $k=>$v){
echo $k." = ".$v."<br />";
}
}
}
When we loop through a multi dimentional array its better to check if the keys are available if the corresponding values are again array and also to check if the array of values have some elements before doing loop.
So here first checking if "crm" is available and if the value i.e. again an array having some elements before doing a loop and its done by the line
if(array_key_exists("crm",$val) && count($val["crm"]) > 0 ){
This is done to avoid further notice like invalid index and invalid argument supplied in foreach if the element is missing or the data array is not present.

You're trying to loop over whole 2-nd level array, but only crm key points to array. Thus, you need to do:
foreach ($newOrders as $crm)
{
if(isset($crm['crm']))
{
foreach ($crm['crm'] as $val)
{
echo $val;
}
}
}
-if you want to get values in crm key. It may not exist, thus, I've added isset check.

Related

Remove the whole array elements, where array element key count < 2 in PHP

Below is my code that output this array:
// update users
$where_in = array('1102','');
$admin_data = $this->db->select('id,email,domain')->where_in('id',$where_in)->get('users')->result();
echo "<pre>";print_r($admin_data);
current output array
1102,
Array
(
[0] => stdClass Object
(
[id] => 1
)
)
1111,
Array
(
[0] => stdClass Object
(
[id] => 1132
)
[1] => stdClass Object
(
[id] => 1133
)
)
I am trying to accomplish by doing this, but not getting expected result.
foreach ($admin_data as $key) {
if (count($admin_data) < 2) {
unset($admin_data);
}
}
Expected result: I want to remove whole array element, where array key less than 2. I wish to get only array with more than 1 key count like below:
1111,
Array
(
[0] => stdClass Object
(
[id] => 1132
)
[1] => stdClass Object
(
[id] => 1133
)
)
I believe you are trying to unset elements within your "$admin_data" array, however you call unset on the array itself. If you pass the index of the array element into your loop, with the element itself, then you can check if the element has less than two inner elements, and unset that element accordingly.
$elementsToRemove = [];
foreach($admin_data as $index => $key) {
if (count($key) < 2) {
$elementsToRemove[] = $index;
}
}
$newArray = array_diff_key($admin_data, array_flip($elementsToRemove));
I'm not sure if I understood, but if you have an array of arrays and want to remove the inner arrays with less than 2 elements, you could do:
<?php
$original = [
["a"],
["b", "c"],
];
$filtered = array_filter(
$original,
function ($innerArray) {
return count($innerArray) >= 2;
}
);
print_r($filtered);
The result is
Array
(
[1] => Array
(
[0] => b
[1] => c
)
)
PHP Fiddle
Check again your code, it contains some logical problems:
foreach ($admin_data as $key) {
if (count($admin_data) < 2) {
unset($admin_data);
}
}
If $admin_data has one item, the if (count($admin_data) < 2) test is true and
unset($admin_data); is executed. That means (simplifying) that the all the contents of $admin_data are deleted.
If $admin_data has two or more items, the if (count($admin_data) < 2) test is never true. And it is so for each iteration.
Both cases are not logical, because you do not need the foreach loop for this test to work. Besides, you might not want to delete $admin_data contents.
What you need to do, is to iterate through $admin_data items, check the item to see if it is an array and if that array has one item, remove the item from the $admin_data array. Or you could create another array only with the valid items.
Here is a possible example of both:
/* unset the item if it is an array with one item */
foreach ($admin_data as $key => $value) {
if (is_array($value) && count($value) === 1) {
unset($admin_data[$key]);
}
}
/* create a new array with the valid items */
$valid_admin_data = [];
foreach ($admin_data as $key => $value) {
if (is_array($value) && count($value) > 1) {
$valid_admin_data[$key] = $value;
}
}
I would also suggest you to read again the foreach documentation. Also, be consistents with names of variables, since it helps avoid misunderstandings: for instance, foreach ($admin_data as $key) could be better named to foreach ($admin_data as $value), since with one variable, you extract the value of current item.

php combines array values in main array

I have total 3 array
First array contains list of titles
Second array contains list of description
third array contains images
I have already combine 1st and 2nd array as a key of first array and value of second array and I also combine 1st and 3rd array as key of 1st and value of 3rd.
Following is my arrays
1 )
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[0] => Array
(
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
)
I want output like
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
Code
foreach ($images as $key => $value) {
$values['image']= $value;
}
$data = array_combine($_POST['title'], $images);
$mainArray = array_combine($_POST['title'], $_POST['Description']);
array_push($mainArray,$data);
echo '<pre>';
print_r($mainArray);
How can I do this?
The code below should produce the format the array as required above, although it is not the most elegant way to flatten an array. It may be worthwhile looking at previous questions like How to Flatten a Multidimensional Array?
$newArr = array();
foreach ( $mainArray as $key => $val ) {
if ( is_array( $val ) ) {
foreach ( $val as $key2 => $val2 ) {
$newArr[$key2] = $val2;
}
} else {
$newArr[$key] = $val;
}
}

How to find parent array key in multidimensional array php

I've tried to adjust many similar solutions that I've found here on stack by none worked for me. Could someone please help me?
This multidimensional array is dynamically generated (contains 55 keys total).
There is variable $age which users enter, and $age correspondents to second array key, in this example [15]. By this key $age I have to find out parent key val $key.
In order to echo final value I need that top level array key ($key). Here is what echo would look like:
$val = $array[$key][$age]["stadij1"]["20-40"];
echo $val;
How do I target top level parent array key([0]) of key [15]?
Array
(
[0] => Array
(
[15] => Array
(
[stadij1] => Array
(
[0-20] => 0
[20-40] => 61
[40-80] => 38
[80-120] => 30
[120-xx] => 27
)
[stadij2] => Array
(
[0-20] => 0
[20-40] => 50
[40-80] => 32
[80-120] => 27
[120-xx] => 24
)...
)...
//my try
$key = array_search($age,$array); //problem is that it returns only first element
$val = $array[$key][$age]["stadij1"]["20-40"];
echo $val;
If I understood correctly, you mean something like:
function findKey($array, $age)
{
foreach ($array as $parentIndex => $parentValue) {
foreach ($row as $index => $value) {
if ($index === $age) {
return $parentIndex;
}
}
}
throw new Exception('key not found');
}

After deleting the particular multidimensional array element in PHP, the Next array elements are not positioning automatically

I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}

Proper Syntax for PHP foreach function with associative arrays

I have the following array named $ingredient_difference in PHP (example output below):
Array (
[total_remaining_ingredients] => Array (
[0] => 2 [1] => 3 [2] => 10
)
[idrecipe] => Array (
[0] => 8 [1] => 10 [2] => 9
)
[value] => Array ( [0] => 1 [1] => 1 [2] => 1 )
)
I'm trying to extract at least the values of idrecipe using 'foreach', but I'm getting undefined index with the following code:
foreach($ingredient_difference as $recipe_output)
{
echo $recipe_output['idrecipe']."<br />";
}
I know the above isn't exactly the way to do it, but this also was not working (undefined index error for 'idrecipe', 'value' and 'total_remaining_ingredients'):
foreach($ingredient_difference as $c => $rowkey)
{
$sorted_idrecipe[] = $rowkey['idrecipe'];
$sorted_value[] = $rowkey['value'];
$sorted_remaining_ingredients[] = $rowkey['total_remaining_ingredients'];
}
What am I missing in my foreach syntax? Or is there a better way?
This foreach construct is also giving undefined index errors:
foreach($ingredient_difference as $rowkey => $index_value)
{
$id_value[$key] = $index_value['idrecipe'];
$value_value[$key] = $index_value['value'];
$tri_value[$key] = $index_value['total_remaining_ingredients'];
}
Answer thanks to ComFreek:
$result_ingredient_difference = array();
$count_id = count($ingredient_difference['idrecipe']);
for ($i=0; $i<$count_id; $i++)
{
$result_ingredient_difference[] = array(
'tri' => $ingredient_difference['total_remaining_ingredients'][$i],
'idrecipe' => $ingredient_difference['idrecipe'][$i],
'value' => $ingredient_difference['value'][$i]
);
}
//rearranged array of $result_ingredient_difference able to call proper indexing with the below
foreach($result_ingredient_difference as $rowkey => $index_value)
{
$id_value[$key] = $index_value['idrecipe'];
$value_value[$key] = $index_value['value'];
$tri_value[$key] = $index_value['tri'];
}
With your first foreach() loop, you iterate over the main array and not over the values of the subarray idrecipe!
foreach($ingredient_difference['idrecipe'] as $value)
{
echo $value;
}
foreach constructs a loop. In your code
foreach($ingredient_difference as $recipe_output) {
echo $recipe_output['idrecipe']."<br />"; }
in the first loop run: $recipe_output is $ingredient_difference[total_remaining_ingredients]
in the second loop run: $recipe_output is $ingredient_difference[idrecipe]
in the third loop run: $recipe_output is $ingredient_difference[value]
because there is no
$ingredient_difference['total_remaining_ingredients']['idrecipe']
$ingredient_difference['idrecipe']['idrecipe']
$ingredient_difference['value']['idrecipe']
you get the error.
to see how the foreach loop works use the examples on http://php.net/manual/de/control-structures.foreach.php
i Expect what you want to do is:
foreach($ingredient_difference['idrecipe'] as $value_of_recipe)
{
echo $value_of_recipe."<br />";
}

Categories