This question already has answers here:
How to get an array of specific "key" in multidimensional array without looping [duplicate]
(4 answers)
Closed 1 year ago.
I have a multidimensional array, that has say, x number of columns and y number of rows.
I want specifically all the values in the 3rd column.
The obvious way to go about doing this is to put this in a for loop like this
for(i=0;i<y-1;i++)
{
$ThirdColumn[] = $array[$i][3];
}
but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
For example (this does not work offcourse)
$ThirdColumn = $array[][3]
Given a bidimensional array $channels:
$channels = array(
array(
'id' => 100,
'name' => 'Direct'
),
array(
'id' => 200,
'name' => 'Dynamic'
)
);
A nice way is using array_map:
$_currentChannels = array_map(function ($value) {
return $value['name'];
}, $channels);
and if you are a potentate (php 5.5+) through array_column:
$_currentChannels = array_column($channels, 'name');
Both results in:
Array
(
[0] => Direct
[1] => Dynamic
)
Star guests:
array_map (php4+) and array_column (php5.5+)
// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
Not yet. There will be a function soon named array_column(). However the complexity will be the same, it's just a bit more optimized because it's implemented in C and inside the PHP engine.
Try this....
foreach ($array as $val)
{
$thirdCol[] = $val[2];
}
Youll endup with an array of all values from 3rd column
Another way to do the same would be something like $newArray = array_map( function($a) { return $a['desiredColumn']; }, $oldArray ); though I don't think it will make any significant (if any) improvement on the performance.
You could try this:
$array["a"][0]=10;
$array["a"][1]=20;
$array["a"][2]=30;
$array["a"][3]=40;
$array["a"][4]=50;
$array["a"][5]=60;
$array["b"][0]="xx";
$array["b"][1]="yy";
$array["b"][2]="zz";
$array["b"][3]="aa";
$array["b"][4]="vv";
$array["b"][5]="rr";
$output = array_slice($array["b"], 0, count($array["b"]));
print_r($output);
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here
This question already has answers here:
Using a string path to set nested array data [duplicate]
(8 answers)
Closed 2 years ago.
I want to find a workaround for the following problem:
I have n vectors(unique), like the following: ("val1", "val2", "val3", ..., "valn" ).
Each vector's length is different.
I want to add any of those in a new array, but using the vector values(val1,val2,val3) elements as sub-elements recursively for the new array, taken from the main vector(val1 => val+1 => val+2 => val+3 => ... val+n => solution), and the last element of the vector is an integer or a string(not a sub-array/vector as the others), which will match with the last element of the new array, and it's new array's soluton/target.
The workaround solution I am applying right now is this:
Let's suppose the target(solution) is the end value of the array(an integer or string).
In this case I suppose to work on a vector with 4 elements, where the last one is the solution.
$vector = array("val1", "val2", "val3", "target");
$count = count($vector);
$new_array = array();
switch($count){
case 1:
....
case 4:
$new_array[$vector[0]][$vector[1]][$vector[2]] = $vector[3];
/*New array will be
$new_array = [
val1 =>
val2 =>
val3 => "target"
];
*/
break;
}
The vectors I am using are many and with different sizes, so the solution/target can be in the 1st element, second, third and so on, so I applied in my switch any cases from 0 to 5 for example, working as wrote above.
I think there could be a better solution, to loop inside a for(or better, a while) cycle
But I am currently having no ideas on how it should be, and I didn't find any workaround in the web.
Does anyone have a soluton for this?
Thanks in advance
You can build the resulting array starting from the most recent nested element:
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$new_array = array_pop($vector);
foreach(array_reverse($vector) as $val) {
$new_array = [$val => $new_array];
}
print_r($new_array);
Hi You can change your code like it:
<?php
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$count = count($vector);
$new_array = array();
$new_array[$vector[$count - 2]] = $vector[$count - 1];
for ($i=($count - 3); $i >= 0; $i--) {
$temp_array = array();
$temp_array[$vector[$i]] = $new_array;
$new_array = $temp_array;
}
print_r($new_array);
And the result will be like it:
Array
(
[val1] => Array
(
[val2] => Array
(
[val3] => Array
(
[val4] => Array
(
[val5] => target
)
)
)
)
)
This question already has answers here:
sort a multi-dimensional associative array?
(3 answers)
Closed 5 years ago.
i have seen several SO answers but none seem to address this very simple situation.
my array looks like the following:
$myArray =
['person_1#gmail.com'] =>
['2017-01-05'] =>
'this is line one'
'this is line two'
['2016-05-05'] =>
'this is another line'
'and this is a fourth line'
['2017-07-10'] =>
'more lines'
'yet another line'
['person_2#gmail.com'] =>
['2015-01-01'] =>
'line for person_2'
within each of the first levels (email address), how would I sort the second level (date yyyy-mm-dd) in descending?
I did try this:
foreach ( $myArray as $emailAddress => $emailAddressArrayOfDates ) {
usort ( $myArray[$emailAddress] );
}
and I also tried to ksort with a function as well with no success.
thank you very much.
Use this:
foreach($myArray as $emailAddressKey=>$datesArray){
krsort($myArray[$emailAddressKey]);
}
print_r($myArray);
or (but i prefer the first option)
foreach($myArray as &$value){
krsort($value);
// this works only if $value is passed by reference. If it's not,
// it will update $value, but not $myArray[$key] as $value is only
// a local variable.
}
print_r($myArray);
This is the sorting method:
krsort — Sort an array by key in reverse order
bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
See a working example here: https://3v4l.org/pok2e
I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));
I have a single array such as this:
array('one','two','three','four','five','six','seven')
I'm using a foreach to iterate through this and I'd like to build an array like this:
array(
array('one'),
array('two')
),
array(
array('three'),
array('four')
),
array(
array('three'),
array('five')
),
array(
array('six'),
array('seven')
)
Any suggestions on how do this?
Thanks!
Use array_chunk.
From the PHP Manual:
array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )
Chunks an array into size large chunks. The last chunk may
contain less than size elements.
In your case you need $output_array = array_chunk($input_array, 2);
And then if you want to convert the leaves to arrays:
function leaves_to_array(&$item, $key)
{
if (!is_array($item))
$item = array($item);
}
array_walk_recursive($output_array, 'leaves_to_array');