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

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

Related

How to convert multiple array to single array [duplicate]

This question already has answers here:
Convert array of single-element arrays to a one-dimensional array
(8 answers)
Closed 3 years ago.
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.
I want to convert this array to single array like.
Convert this :-
Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
Convert To :-
Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
To "Merge" multiple arrays into one, you can use array_merge()
A good example would be:
$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);
Something like this should do:
while($row = $result->fetch_array(MYSQLI_NUM)) {
$users[] = $row[0];
}
Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.
$arr = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');
$one_dim_array = array_merge(...$arr);
//or better
$one_dim_array = array_column($arr,0);
echo "<pre>".var_export($one_dim_array, true);
Result:
array (
0 => 'user',
1 => 'user1',
2 => 'user2',
)
Try it yourself : Sandbox
Another alternative, aside from array_merge, for the case of an arbitrary number of subarrays, you could use array_reduce and build your final array:
$inArray = [['user'],['user1'],['user2'],['user3'],['user8'],['user7'],['user6']];
$inArray = array_reduce($inArray, function($arr, $elem){
$arr[] = $elem[0];
return $arr;
});
Of course, the straightforward solution would be to use array_merge:
$inArray = array_merge(...$inArray);

foreach value with key outside foreach [closed]

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

How can i get list of values from array in laravel?

I have array such as below
Array ( [0] => 2 [1] => 4 [2] => 5)
In which 2,4,5 is value and i need only list of value like [2,4,5] is it possible in laravel??
$list=[];
$arr=array( 0=> 2,1 => 4,2 => 5);// This is the original array
foreach($arr as $k=>$v ){
array_push($list,$v);
}
// Now,$list is what you need! [2,4,5]
I don't think this question is about laravel, this is basic knowledge of PHP array!
Got list using below command.
implode(',', $array);

I want to sort the array by keys in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an array, $data, in the form of :
Array
(
[1] => Array
(
[group_exp] => Group 2
[cat_exp] => Category 3
[sub_exp] => Sub Category 4
)
[2] => Array
(
[group_exp] => Group 3
[cat_exp] => Category 4
[sub_exp] => Sub Category 5
)
)
but i want to save this array in this form :
Array
(
[0] => Array
(
[group_exp] => Group 2
[cat_exp] => Category 3
[sub_exp] => Sub Category 4
)
[1] => Array
(
[group_exp] => Group 3
[cat_exp] => Category 4
[sub_exp] => Sub Category 5
)
)
As the comments has shown, use array_values to reorder the indexes if the array already is in the correct order.
$array = array_values($array);
If the array should be sorted by its indices (if their inherent order is not sorted, such as [2], [1], [3], sort the array by key first:
ksort($array);
$array = array_values($array);
If you just want to reduce your indexes by one, rather than all the way to zero, consider using a for loop approach:
$length = count($data);
for($i = 1; $i <= $length; $i++){
$data[$i-1] = $data[$i];
unset($data[$i]);
}

How to assign new numerical keys to an array and sort based on the original keys? [duplicate]

This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
How to sort an array by keys in an ascending direction?
(3 answers)
Closed 2 years ago.
I have an array with numerical indices, which looks like this (after I unset some elements):
$array = [
23 => 'banana',
3 => 'apple',
5 => 'pear',
];
Which function do I use to reorder them based on their key order to:
$array = [
0 => 'apple',
1 => 'pear',
2 => 'banana',
];
I tried some of the sort functions but none of them provided the output I need.
If you want to sort the array by key value use ksort():
ksort($array);
print_r($array);
Output:
Array
(
[3] => apple
[5] => pear
[23] => banana
)
That will preserve the keys however. To reassign keys for an array from 0 onwards use array_values() on the result:
ksort($array);
$array_with_new_keys = array_values($array); // sorted by original key order
print_r($array_with_new_keys);
Output:
Array
(
[0] => apple
[1] => pear
[2] => banana
)
ksort() will sort by key, then get the values with array_values() and that will create a new array with keys from 0 to n-1.
ksort($array)
$array = array_values( $array );
Of course, you don't need ksort if it's already sorted by key. You might as well use array_values() directly.
$arrayOne = array('one','two','three'); //You set an array with certain elements
unset($array[1]); //You unset one or more elements.
$arrayTwo = array_values($arrayOnw); //You reindex the array into a new one.
print_r($arrayTwo); //Print for prove.
The print_r results are:
Array ( [0] => one [1] => three )

Categories