foreach value with key outside foreach [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a few foreaches which show a total of some numbers.
One of them is this one:
foreach ($lijst['palen'] as $key => $valuepalen)
{
echo $valuepalen ."x Bekaclip palen (48mm / lengte " . $??? . " cm" . "\n";
}
And then there is this one which contains the values I need:
foreach ($optellen as $key => $hoogtevalue)
{
}
The values I need is $hoogtevalue which contains 100 and 110.
But if I insert $hoogtevalue in $??? it only shows the last submitted number 110.
I want to show it like this:
......... lengte is 100
......... lengte is 110

It seems to me that you are trying to map the values from one array to the other, by the position that they sit in the array, rather than by their existing key.
You could use array_map with null as the first parameter to create a new array that consists of pairs from each. (I've added a print_r of the mapped array below to demonstrate the data structure.)
You can then just loop through the pairs.
<?php
$one = [ 63 => 2, 123 => 2];
$two = [ 1 => 100, 3 => 110];
$pairs = array_map(null, $one, $two);
print_r($pairs);
foreach($pairs as $pair)
printf("%d = %d\n", $pair[0], $pair[1]);
Output:
Array
(
[0] => Array
(
[0] => 2
[1] => 100
)
[1] => Array
(
[0] => 2
[1] => 110
)
)
2 = 100
2 = 110
Alternatively you could use the array_values function on both arrays to re-index them and then use keys for association.

This will handle it:
foreach ($lijst['palen'] as $valuepalen) {
foreach ($optellen as $hoogtevalue) {
echo $valuepalen."x Bekaclip palen (48mm / lengte ".$hoogtevalue".cm \n";
}
}

Related

Add one more element to array in loop with PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have array like below:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];
i want to add one more element to array $arr by "link"=>"uploads/hello.jpg"
My expected result:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg","link"=>"uploads/hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg","link"=>"uploads/abc.jpg"]];
Any solution for this thank.
You can iterate over the array using foreach, passing a reference into the loop to allow the values to be modified directly:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];
foreach ($arr as &$a) {
$a['link'] = 'uploads/' . $a['pict'];
}
print_r($arr);
Output:
Array
(
[0] => Array
(
[id] => 001
[name] => Hello
[pict] => hello.jpg
[link] => uploads/hello.jpg
)
[1] => Array
(
[id] => 002
[name] => Abc
[pict] => abc.jpg
[link] => uploads/abc.jpg
)
)
Demo on 3v4l.org
You can iterate over each element in the array and set it that way.
for ($i = 0; $i < count($arr); i++) {
$arr[$i]['link'] = 'uploads/'.$arr[$i]['pict'];
}
foreach($arr as $key => $value){
$arr[$key]['link'] = "uploads/".$value['pict'];
}
Use the foreach loop to modify the original array. The $key value is used to refer to each index in the array.

How to format an php array to desired result [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need to display some data in the chart. Basically i have an array from database which looks like this-
[
[0] =>[
[user_type] => 'Manager'
[total_count] => 3
],
[1] =>[
[user_type] => 'Director'
[total_count] => 2
]
]
There is one more user_type which is Trainee . If user Trainee has 0 Total_count it is not coming in above array. So i need to add manually. So first will check which user_type is not exist in above array out of 3 user_types. If not exist then just need to add total_count 0.
And finally my desired array should look like this-
[
['labels'] =>['Manager','Director','Trainee],
['dataset'] => [ 3, 2, 0 ]
]
Please notice here, Proper sequence is very important. So in above array Manager has 3, Director has 2 and Trainee has 0 total count.
Thanks in advance!
Try the below code maybe It will help.
/*
using array column will get the result in
Array ( [Manager] => 3 [Director] => 2 )
*/
$array_column = array_column($array, 'total_count', 'user_type');
//Create new array like below
$add_array = array('Manager'=>'0', 'Director'=>'0', 'Trainee'=>'0',);
//using array_merge merge add_array and array_column
$new_array = array_merge($add_array, $array_column);
//using array_walk_recursive get the requird result
array_walk_recursive($new_array, function($item, $key) use (&$final_array){
$final_array['labels'][]=$key;
$final_array['dataset'][]=$item;
});
echo "<pre>";
print_r($final_array);
?>
Case 1- if Trainee is not there in array
DEMO
Case 2 - If Manager and Director both are not there in array
DEMO
Case 3- if Director is not there - DEMO
Here is the script you can use with array_combine and array_map with splat(...) operator
$arr = array_combine(['labels','dataset'],array_map(null, ...$arr));
if(!in_array('Trainee',$arr['labels'])){
array_push($arr['labels'],'Trainee');
array_push($arr['dataset'],0);
}
print_r($arr);die;
array_combine — Creates an array by using one array for keys and another for its values
Note:- In array_map NULL can be passed as a value to callback to perform a zip
operation on multiple arrays. If only array1 is provided, array_map()
will return the input array. In short to perform transpose of array operation
Working demo
Output:-
Array
(
[labels] => Array
(
[0] => Manager
[1] => Director
[2] => Trainee
)
[dataset] => Array
(
[0] => 3
[1] => 2
[2] => 0
)
)
Try this
$arr = array_combine(['labels','dataset'], array_map(null, $arr));
Make a function for adding non-existing user_type into array
function setUserType($userType, $array) {
if(!in_array($userType, $array['labels'])){
array_push($array['labels'], $userType);
array_push($array['dataset'], 0);
}
return $array;
}
Call function by any user_type like 'Manager', 'Trainee', 'Director'
$arr = setUserType('Trainee', $arr);
Or make an array of all user types and run a loop
foreach(['Manager', 'Trainee', 'Director'] as $type) {
$arr = setData($type, $arr);
}
Print and show the final value
print_r($arr);
die();
Demo https://3v4l.org/UbiXn
Try it
$array = array();
foreach($yourArr as $row)
{
$array['labels'][] = $row['user_type'];
$array['dataset'][] = $row['total_count'];
}
print_r($array);

Efficient way of traversing a complicated Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a database table that would return an array something like this
$roles['admin'] = 'app1,app2,app3';
$roles['moderator'] = 'app2,app3';
Now I want to traverse this array to show in my view, But instead of showing all apps inside each role, i would like to show all roles inside each app.
So ideally i would like the above array to become this
$apps['app1'] = 'admin';
$apps['app2'] = 'admin,moderator';
$apps['app3'] = 'admin,moderator';
I have been trying to solve this for 2 hours now, but for some reason I can't find an efficient way of doing this.
The following will traverse your array and load it into the appropriate array. It works by going through each part of the array and traversing it.
<?php
$apps = array();
foreach($roles as $key1 => $value1){
$parts = explode(',', $value1);
foreach($parts as $key2 => $value2){
$apps[$value2] .= (strlen($apps[$value2])>0)?",":"").$key1;
}
}
?>
You can map one array to the other by using array_reduce, array_keys and explode to turn your CSV values into arrays
$apps = array_reduce(array_keys($roles), function($apps, $key) use ($roles) {
foreach (explode(',', $roles[$key]) as $app) $apps[$app][] = $key;
return $apps;
}, []);
Note that the result is slightly different to what you wanted in that the values are themselves arrays instead of comma separated strings.
Array
(
[app1] => Array
(
[0] => admin
)
[app2] => Array
(
[0] => admin
[1] => moderator
)
[app3] => Array
(
[0] => admin
[1] => moderator
)
)
If you really need CSV values, add this
$apps = array_map(function($list) {
return implode(',', $list);
}, $apps);
which produces
Array
(
[app1] => admin
[app2] => admin,moderator
[app3] => admin,moderator
)

Combining two PHP arrays with some conditional addition thrown in [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've got an unusual problem, but I'm fairly certain it's not impossible to solve.
Consider the two arrays below.
Array ( [0] => 1 [1] => 2 [2] => 2 )
Array ( [0] => 879 [1] => 482 [2] => 1616 )
I need to add the values in second array where the values in the first array are the same so that I would end up with...
Array ( [0] => 879 [1] => 2098 )
How might this be accomplished? Thanks in advance!
This isn't a full-proof way of completing this task, but it achieves the goal you desire. What's happening here is we're looping through your first array (the keys) and using the set values of these keys to add the values from the second array:
$new = array();
foreach($keys as $i => $key) {
if(!isset($new[$key])) { $new[$key] = 0; }
$new[$key] += $vals[$i];
}
Example/Demo
Notes
$keys being your first array: $keys = array(1, 2, 2);
$vals being your second array: array (879, 482, 1616);
As I stated, this isn't full-proof. You will need to modify it to ensure integrity, but it is a start that shows the flow of how you can go about doing what you require.

how to loop over this array to obtain only the number 6 and 2? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to loop over the array called $res, but I want to obtain only the values 6 and 2, for each name it is an id, is its with a foreach o just a normal for? I am confused because the array has two arrays insiden and it increments if I add a new name like 'Joe'
$arrayDirectory = array('Nick', 'Alex');
$res = array();
foreach($arrayDirectory as $user) {
$res[] = $obj->obtainID($user);
}
echo print_r($res);
Array ( [0] => Array ( [0] => Array ( [id_usuario] => 6 [0] => 6 ) ) [1] => Array ( [0] => Array ( [id_usuario] => 2 [0] => 2 ) ) ) 1
foreach ($res as $item) {
echo $item[0][0];
}
Or
foreach ($res as $item) {
echo $item[0]['id_usuario'];
}
Depending on what you are looking for
With PHP5.3 you can also use array_map() with a lambda
$idUsarios = array_map(function ($item) {
return $item[0]['id_usario'];
}, $res);
Change
$res[] = $obj->obtainID($user);
to
$user = $obj->obtainID($user);
$res[] = $user[0]['id_usuario'];

Categories