I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:
$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
$arr = array('val' => $row);
echo $row;
}
print_r($arr);
So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.
My question would be how can I store each instance of row in my array?
Create a new array, fill it:
$array = array("v1", "v2", "v3", "v4");
$newArray = array();
foreach($array as $row){
// notice the brackets
$newArray[] = array('val' => $row);
}
print_r($newArray);
It looks like you are storing your array wrong.
Try adjusting the $arr = array('val' => $row);
to:
$arr[] = array('val' => $row);
This will set it so you pick up each line as a separate array which you can easily navigate through.
Hope this helps!
If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.
$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);
While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.
Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.
Related
How to change key array php from
array(
[0]=>Joni
[1]=>Jono
[2]=>Riki
[3]=>Budi
);
Change index to:
array(
[nominal]=>Joni
[nominal]=>Jono
[nominal]=>Riki
[nominal]=>Budi
);
you can make a multi-dimensional array for this purpose
$arr = array('a','b','c','d');
for($i=0;$i<count($arr);$i++){
$newArr['nominal'][$i] = $arr[$i];
}
print_r($newArr);
The expected outcome you want is not possible at all, because same indexes will be over-written in single-dimensional array.
Check this to understand what i said above:- https://eval.in/954556
Now there are 2 closer possiblities of outcomes, which i am going to mention:-
$possibility1 = [];
$possibility2 =[];
foreach($array as $arr){
$possibility1[] = ['nominal'=>$arr];
$possibility2['nominal'][] = $arr;
}
print_r($possibility1);//first closer possibility
print_r($possibility2);//second closer possibility
Output:- https://eval.in/954559
I have an array of numeric subarrays. I want to sort all the subarrays, and then sort the whole array, and remove duplicates. Using sort($val) doesn't work, so I found the following workaround with $derp, which I find insanely stupid:
$arr = array( array(5,6), array(1,2), array(6,5) );
foreach ($arr as $key => $val) {
$derp = $val;
sort($derp);
$arr[$key] = $derp;
}
sort($arr);
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
The result is array( array(1,2), array(5,6) ). Is that is the correct way to do this in PHP, or is there a better and shorter way?
I created a pastebin as a response to the first answer: pastebin.com/Y5vNvKKL
This question is not anymore just about a less goofy way to write this: Now the question is:Why does sort() in array_work() not give the same result as sort() in foreach?
By the way: This is about finding the partitions of multisets.
I'd approach it like this:
array_walk($arr, 'sort');
$deduped = array();
foreach ($arr as $val) {
$deduped[serialize($val)] = $val;
}
$arr = array_values($deduped);
Let's say I have a data set in PHP that is in the form of:
$array = [{"prior":"0","id":"61039","type":"todo"},
{"prior":"1","id":"70341","type":"todo"},
{"prior":"3","id":"39104","type":"todo"},
{"prior":"4","id":"70315","type":"todo"},
{"prior":"6","id":"72050","type":"todo"},
{"prior":"7","id":"72329","type":"todo"},
{"prior":"8","id":"73992","type":"todo"}]
I want to process this array of arrays so that I have a single array with integer indexes and the values of only id.
It's trivial to simple use loops:
$data = array();
foreach($array as $item){
$data[] = $item['id'];
}
What I want to know, is there a way to do this, disregarding efficiency, using the built in array functions of PHP (with no loops), or am I stuck using the foreach loop?
You can use array_map() for this:
$data = array_map(function ($el) { return $el['id']; }, $array);
Note that this still has to perform the looping internally; it's just not shown explicitly as in a foreach loop. This approach will be far less efficient than a plain 'ol foreach.
Demo
With PHP >= 5.5.0:
$array = json_decode($array, true);
$ids = array_column($array, 'id');
this is the output of my array
[["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]]
but I would like this to look like
[1,1,1,1,1,1,1]
how would this be achieved in php, it seems everything I do gets put into an object in the array, when I don't want that. I tried using array_values and it succeeded in returning the values only, since I did have keys originally, but this is still not the completely desired outcome
$yourArray = [["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]];
use following code in PHP 5.3+
$newArray = array_map(function($v) {
return (int)$v[0];
}, $yourArray);
OR use following code in other PHP version
function covertArray($v) {
return (int)$v[0];
}
$newArray = array_map('covertArray', $yourArray)
You could always do a simple loop...
$newArray = array();
// Assuming $myArray contains your multidimensional array
foreach($myArray as $value)
{
$newArray[] = $value[0];
}
You could beef it up a little and avoid bad indexes by doing:
if( isset($value[0]) ) {
$newArray[] = $value[0];
}
Or just use one of the many array functions to get the value such as array_pop(), array_slice(), end(), etc.
I have this kind of an array containing single-element arrays:
$array = [[88868], [88867], [88869], [88870]];
I need to convert this to one dimensional array.
Desired output:
[88868, 88867, 88869, 88870]
Is there any built-in/native PHP functionality for this array conversion?
For your limited use case, this'll do it:
$oneDimensionalArray = array_map('current', $twoDimensionalArray);
This can be more generalized for when the subarrays have many entries to this:
$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);
The PHP array_mergeĀDocs function can flatten your array:
$flat = call_user_func_array('array_merge', $array);
In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:
$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);
See as well: Turning multidimensional array into one-dimensional array
try:
$new_array = array();
foreach($big_array as $array)
{
foreach($array as $val)
{
array_push($new_array, $val);
}
}
print_r($new_array);
$oneDim = array();
foreach($twoDim as $i) {
$oneDim[] = $i[0];
}
Yup.
$values = array(array(88868), array(88867), array(88869), array(88870));
foreach ($values as &$value) $value = $value[0];
http://codepad.org/f9KjbCCb
foreach($array as $key => $value){
//check that $value is not empty and an array
if (!empty($value) && is_array($value)) {
foreach ($value as $k => $v) {
//pushing data to new array
$newArray[] = $v;
}
}
}
For a two dimensional array this works as well:
array_merge(...$twoDimensionalArray)
While some of the answers on the page that was previously used to close this page did have answers that suited this question (like array_merge(...$array)). There are techniques for this specific question that do not belong on the other page because of the input data structure.
The sample data structure here is an array of single-element, indexed arrays.
var_export(array_column($array, 0));
Is all that this question requires.
If you ever have a daft job interview that asks you to do it without any function calls, you can use a language construct (foreach()) and use "array destructuring" syntax to push values into a result variable without even writing a body for the loop. (Demo)
$result = [];
foreach ($array as [$result[]]);
var_export($result);
Laravel also has a flattening helper method: Arr::flatten()