I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it
Related
I've been stuck on this for the better part of the day and I'm out of ideas. I have an array like this:
Array
(
[rank] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[name] => Array
(
[0] => 'Hideki'
[1] => 'Rory'
[2] => 'Sam'
[money] => Array
(
[0] => '$100'
[1] => '$200'
[2] => '$500'
)
)
and I have the task to create an array with the following format from it:
Array
(
[Hideki] => Array
(
[rank] => 1
[money] => '$100'
)
[Rory] => Array
(
[rank] => 2
[money] => '$200'
[Sam] => Array
(
[rank] => 3
[money] => '$500'
)
)
The catch is that 'rank' and 'money' have to be dynamic names
It should be simple as that:
$new = [];
foreach($array['name'] as $key => $name) {
$new[$name] = [
'rank' => $array['rank'][$key],
'money' => $array['money'][$key]
];
}
Little late but here my answear. My approach was to use the array_walk() function.
$array = [
'rank' => [1,2,3],
'name' => ['Hideki', 'Rory', 'Sam'],
'money' => ['$100', '$200', '$500'],
];
$i = 0;
$newArray = [];
array_walk($array['name'], function($name) use (&$i, $array, &$newArray) {
$newArray[$name] = ['rank'=> $array['rank'][$i], 'money' => $array['money'][$i]];
$i++;
});
print_r($newArray);
Run your first array through a foreach loop referencing only the "name" key and using key=>value pairs. Then reference the other keys from the first array when you build the new array, setting the value as the key to the second array.
You will need to first get the keys using array_keys() and use a nested foreach to loop through all the keys.
Example:
$keys1 = array_keys($array1);
foreach ($array1['name'] as $key => $value) {
$val2 = array();
foreach ($keys1 as $k){
if ($k != 'name') $val2[$k] = $array1[$k][$key];
}
$array2[$value] = $val2;
}
I've this type of array in PHP:
Array(
[100] => Array(
[1] => Array (
[AVA_Date] => 2019-04-18
[ROO_Id] => 100
[RAT_Id] => 9
)
[2] => Array (
[AVA_Date] => 2019-04-20
[ROO_Id] => 100
[RAT_Id] => 10
)
[4] => Array (
[AVA_Date] => 2019-04-21
[ROO_Id] => 100
[RAT_Id] => 10
)
[7] => Array (
[AVA_Date] => 2019-04-22
[ROO_Id] => 100
[RAT_Id] => 9
)
)
)
I would like to merge items on ROO_Id and RAT_Id.
Then, for the AVA_Date, I need to list them under a new array in the current array.
So, the desired output is:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Here what I have tried:
$newArrOtherRooms = array_reduce($newArr, function($acc, $val) {
$room = array_search($val['ROO_Id'], array_column($acc, 'ROO_Id'));
$rate = array_search($val['RAT_Id'], array_column($acc, 'RAT_Id'));
if($rate == $room && $room > -1) {
array_push($acc[$room]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
But it doesn't work like I want.
There are a couple of issues with your code. Firstly, you need to wrap the array_reduce with a foreach over the outer level of $newArr. Secondly, your call to array_search doesn't consider the fact that a ROO_Id or RAT_Id value might exist more than once in the array, as it only returns the first key at which it finds the value. To work around this, you can use array_keys to get an array of key values for each ROO_Id and RAT_Id value, and then take the intersection of those two arrays using array_intersect to see if both are present in the same element. If so, you update that element, otherwise you create a new one:
foreach ($newArr as $key => $array) {
$newArrOtherRooms[$key] = array_reduce($array, function($acc, $val) {
$room = array_keys(array_column($acc, 'ROO_Id'), $val['ROO_Id']);
$rate = array_keys(array_column($acc, 'RAT_Id'), $val['RAT_Id']);
$common = array_intersect($room, $rate);
if(!empty($common)) {
array_push($acc[current($common)]['AVA_Date'], $val['AVA_Date']);
}
else {
$new_arr = $val;
$new_arr['AVA_Date'] = [$val['AVA_Date']];
array_push($acc, $new_arr);
}
return $acc;
},[]);
}
print_r($newArrOtherRooms);
Output:
Array(
[100] => Array(
[0] => Array (
[AVA_Date] => Array (
[0] => 2019-04-18
[1] => 2019-04-22
)
[ROO_Id] => 100
[RAT_Id] => 9
)
[1] => Array (
[AVA_Date] => Array (
[0] => 2019-04-20
[1] => 2019-04-21
)
[ROO_Id] => 100
[RAT_Id] => 10
)
)
)
Demo on 3v4l.org
There is absolutely no reason to be making all of those iterated function calls.
Use a nested loop to iterate the subset of data for each room, group on the room "rate id", and push all "available date" values into a subarray in the respective group. When the subset of data is fully iterated, push its grouped data into the result array.
Code: (Demo)
$result = [];
foreach ($newArr as $rooId => $rows) {
$groups = [];
foreach ($rows as $row) {
if (!isset($groups[$row['RAT_Id']])) {
$row['AVA_Date'] = (array) $row['AVA_Date'];
$groups[$row['RAT_Id']] = $row;
} else {
$groups[$row['RAT_Id']]['AVA_Date'][] = $row['AVA_Date'];
}
}
$result[$rooId] = array_values($groups);
}
var_export($result);
Output:
array (
100 =>
array (
0 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-18',
1 => '2019-04-22',
),
'ROO_Id' => 100,
'RAT_Id' => 9,
),
1 =>
array (
'AVA_Date' =>
array (
0 => '2019-04-20',
1 => '2019-04-21',
),
'ROO_Id' => 100,
'RAT_Id' => 10,
),
),
)
Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)
I have an array ($myArray) which looks like
Array ( [0] =>
Array ( [0] =>
Array (
[Date] => 1776-08-08
[Color] => Yellow
[Description] => Rotten
) )
[1] => Array ( )
[2] =>
Array ([0] =>
Array (
[Date] => 2018-05-13
[Color] => Red
[Status] => Fresh
)
[1] =>
Array (
[Date] => 1991-03-29
[Color] => Green
[Status] => Fresh ) )
I loop though the content for the values of Date using
array_walk_recursive($myArray, function($v, $k){
if ($k == "Date") echo $v . PHP_EOL;
This would get me the correct output.
1776-08-08 2018-05-13 1991-03-29
I want to add the output into an array and even if the value is null (ie[1] above) to still set an empty array.
For example $newArray =
Array ( [0] => 1776-08-08 )
Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )
Given your example, an option is to use array_column() on each of the items in the outermost array, which is easy with the array_map() function.
$input = array(
array(
array(
"Date" => "1776-08-08",
"Color" => "Yellow",
"Description" => "Rotten",
),
),
array(
),
array(
array(
"Date" => "2018-05-13",
"Color" => "Red",
"Status" => "Fresh",
),
array(
"Date" => "1991-03-29",
"Color" => "Green",
"Status" => "Fresh",
),
),
);
$output = array_map(function($sub_arrays) {
return array_column($sub_arrays, "Date");
}, $input);
print_r($output);
The above will output something like:
Array
(
[0] => Array
(
[0] => 1776-08-08
)
[1] => Array
(
)
[2] => Array
(
[0] => 2018-05-13
[1] => 1991-03-29
)
)
You'll need to do a normal foreach loop for the top-level, and then use array_walk_recursive for the nested arrays.
$newArray = array();
foreach ($myArray as $el) {
$temp = array();
array_walk_recursive($el, function($v, $k) use (&$temp) {
if ($k == "Date") {
$temp[] = $v;
}
});
$newArray[] = $temp;
}
DEMO
I'm looking for an elegant way to turn this array:
Array (
[foo] => 1
[bar] => 1
[zim] => 3
[dib] => 6
[gir] => 1
[gaz] => 3
)
Into this array:
Array (
[1] => Array ( foo, bar, gir ),
[3] => Array ( zim, gaz ),
[6] => Array ( dib )
)
Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.
Thanks!
$input = array(
'foo' => 1,
'bar' => 1,
'zim' => 3,
'dib' => 6,
'gir' => 1,
'gaz' => 3
)
$output = array();
foreach ( $input as $k => $v ) {
if ( !isset($output[$v]) ) {
$output[$v] = array();
}
$output[$v][] = $k;
}
I think this will do it just fine:
foreach ($arr1 as $k => $val) $arr2[$val][] = $k;
where $arr1 is the original array outputting the new array to $arr2.