Converting single array into multi dimensional array (grouping ) based on key - php

Lets say I have the following array:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
What I'm now trying to do is to convert this array into a multidimensional array every time the number changes in the key.
I know we have to use explode("__", $key), but I can't work out how to convert it to a multidimensional array so it would appear something like the following:
Array
(
Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
I suspect it's not too difficult but I'm frying my brain trying to work it out.

Simple for loop should do it:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
foreach($arr as $k =>$v) {
$res[explode("__", $k)[1]][$k] = $v;
}
You can use array_values if you don't want the extra key in the upper array.
Live example: 3v4l

Array_chunk seems to be enough.
Array_chunk splits an array with n number of items.
The third argument is to preserve keys.
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
$result = array_chunk($arr, 2, true);
print_r($result);
Output:
Array
(
[0] => Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
[1] => Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
https://3v4l.org/s57ua

Related

Why cant slice or something like that of my arrays with php

I have lot arrays and i want to only print number of 2 and first arrays
i use array_slice but there is still a problem
Arrays:
Array
(
[0] => 441
[1] => Awesome
)
Array
(
[0] => 570
[1] => Noons
)
Array
(
[0] => 571
[1] => Roods
)
I need to like this:
Array
(
[0] => 441
[1] => Awesome
)
Array
(
[0] => 570
[1] => Noons
)
Basically you seem to only need:
array_slice(array_unique(array_column($Myarrays, 'nidtitle')), 0, 2);
This should be done instead of the entire code you use to generate the arrays.
Short explanation:
array_column will get the element nidtitle from each "row" (array entry) in $Myarrays
After that we run that column through a unique function
Then we get the first 2 elements with an array_slice
This should do the job:
$finalarray = array_slice($Myarray, 0, 2);
print_r($finalarray);
You can use array_slice to get the items you want.
$arr = array(Array(441,"Awesome"),
Array(570,"Noons"),
Array(571,"Roods"));
$two = array_slice($arr, 0,2);
Var_dump($two);
Array_slice second parameter is where the slice should start.
Third parameter is count of values to slice.
https://3v4l.org/NPcJT

How do I make an array without using array_count_values()?

I have an array, $arrayName = array(1,2,1,3,4,3,2,5);. I want the result as:
Array (
[1] => 2
[2] => 2
[3] => 2
[4] => 1
[5] => 1
)
Without using array_count_values(), what is the logic behind array_count_values()?
This method will only loop each value once compared to other methods posted here.
Instead of looping the full array I get unique values and count them with array_keys and count.
$arrayName = array(1,2,1,3,4,3,2,5);
$values = array_unique($arrayName);
Foreach($values as $val){
$count[$val] = count(array_keys($arrayName, $val));
}
Var_dump($count);
https://3v4l.org/EGGJq
In your example I think my method may actually be slower than looping the full array, but if this was a large array there may be a benefit of not looping the full array.
The best solution is to use array_count_values function. That counts frequency of values in an array.
See this - http://php.net/manual/en/function.array-count-values.php
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
However, If you don't want to use that function, you can do an ugly way of for loop.
$arrayName = array(1,2,1,3,4,3,2,5);
$resultArray = array();
foreach($arrayName as $value) {
$resultArray[$value] = isset($resultArray[$value]) ? $resultArray[$value] + 1 : 1;
}
print_r($resultArray); // Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 1 [5] => 1 )
Counting frequencies of array elements

PHP multidimensional associative array [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 3 months ago.
I am new to php & I'm not sure that this can be done, but I am hoping that someone knows how to. I've collected all the data that I need to submit but now I need to reformat it before I can json_encode to send to the database.
Basically, I have 1 parent array($data) containing 3 sub-arrays ($hours, $WId, $Pid). I need to create associative arrays for each index position & join them together.
Here is my parent array:
$data = array(
'hours' => array(),
'wId' => array(),
'phaseId' => array(),
);
Here is what currently returns when I print_r each of these arrays:
Array ( [hours] => Array ( [0] => 0.5 [1] => 1 [2] => 2 ) )
Array ( [wId] => Array ( [0] => 10, [1] => 9, [2] => 8, ) )
Array ( [phaseId] => Array ( [0] => 20, [1] => 20, [2] => 19, ) )
I need to take these "vertical" arrays & turn them in to "horizontal" arrays per index, using thearray name as the $key & the value for that index as $value. Here is what I need to return.... (Syntax is probably wrong but you can get the idea.)
Array[1] ("hours" => 0.5, "wId" => 10, "phaseId" => 20)
Array[2] ("hours" => 1, "wId" => 9, "phaseId" => 20)
Array[3] ("hours" => 2, "wId" => 8, "phaseId" => 19)
Is there a function that will allow me to do this easily? I saw how to join & merge them together but not sure how to set the array name (hours, etc) as the $key & the value for each index as $value. I need to loop it too because the length of the arrays will vary. (But they will always the same length as each other, so index should still work as what needs to be collected.)
Any suggestions would be greatly appreciated :)
<?php
// set up your output array
$result = array();
// loop through $data, exposing $name for later use
foreach ($data as $name => $array) {
// loop through each named array and set the desired value
// using the current $key and $name
foreach ($array as $key => $value) {
$result[$key][$name] = $value;
}
}
// tada!
print_r($result);
NOTE: In your desired results in your question, you had the parent Array keys starting at 1. This answer assumes that's a typo and you actually wanted them to match the input. If you indeed wanted it to start at one, just change this line in my answer:
$result[$key+1][$name] = $value;

Fetching a multidimensional array

I am trying to edit a plugin that is fetching a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.
What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.
The current variable
$arrayslides
returns several subarrays that look like something like this (I remove unimportant variables for the sake of briefness):
Array (
[0] => Array (
[slide_active] => 1
)
[1] => Array (
[slide_active] => 0
)
)
What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable
$arrayslides
I have tried a few array functions but have not had any luck. Any suggestions?
$arrayslides = array(0 => array ( 'slide_active' => 1, 'other_data' => "Mark" ),
1 => array ( 'slide_active' => 0, 'other_data' => "ABCDE" ),
2 => array ( 'slide_active' => 1, 'other_data' => "Baker" ),
3 => array ( 'slide_active' => 0, 'other_data' => "FGHIJ" ),
);
$matches = array_filter($arrayslides, function($item) { return $item['slide_active'] == 1; } );
var_dump($matches);
PHP >= 5.3.0
I know its not so efficient but still
foreach ($arraySlides as $key => $value)
{
if(in_array('0', array_values($value))
unset($arraySlides[$key]);
}

Combining and eliminating keys value pairs in array

A PHP question about arrays. Suppose we have two arrays:
[first] => Array
(
[0] => users
[1] => posts
[2] => comments
)
[second] => Array
(
[users] => the_users
[posts] => the_posts
[comments] => the_comments
[options] => the_options
)
How can I compare these two arrays? Meaning, how can we check whether or not the value in the first array is equal to the key in the second array (array_flip?) after combining them somehow (array_merge?). And whichever value/key pair matches, remove them from the array.
Basically, the end result would be the two arrays combined, duplicates removed, and the only index will be:
[third] => Array
(
[options] => the_options
)
try this:
$third = array_diff_key($second,array_flip($first));
There could be a built-in function for this, but if there isn't, try:
$third = array();
foreach(array_keys($second) as $item)
if(!in_array($item, $first))
$third[$item] = $second[$item];
Note that this assumes that $first will not have an item that doesn't have a corresponding key in $second. To account for this, you could have an additional loop (I don't know what you would set the value in $third to for these, maybe null:
foreach($first as $item)
if(!in_array($item, array_keys($second)))
$third[$item] = null;
This is pretty simple to do and this way is extremely efficient:
$third = $second;
foreach($first as $value)
{
if (isset($third[$value]))
{
unset($third[$value]);
}
}
this is the answer to ur question
$first= array
(
"0" => "users",
"1" => "posts",
"2" => "comments"
);
$firstf=array_flip($first);
$second = array
(
"users" => "the_users",
"posts" => "the_posts",
"comments" => "the_comments",
"options" => "the_options"
);
$third=array_diff_key($second,$firstf);
print_r($third);

Categories