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');
Related
I know how to get all array keys starting with a particular string in a single array >> How to get all keys from a array that start with a certain string?
But what would be the way to go for multidimensional arrays?
For instance, how to find all keys starting with 'foo-' in:
$arr = array('first-key' => 'first value'.
'sceond-key' => 'second value',
array('foo-1' => 'val',
'bar'=> 'value',
'foo-2' => 'val2')
);
Many thanks, Louis.
You can still apply the solution from the linked question, but with an additional outer filter.
$outputArray = array_filter(
$inputArray,
function ($element) {
return ! is_array($element)
|| ! empty(
array_filter($element, function($key) {
return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY)
);
}
);
See https://3v4l.org/NsgpR for working code.
PHP Manual: is_array()
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));
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);
I have an associative array of data and I have an array of keys I would like to remove from that array (while keeping the remaining keys in original order -- not that this is likely to be a constraint).
I am looking for a one liner of php to do this.
I already know how I could loop through the arrays but it seems there should be some array_map with unset or array_filter solution just outside of my grasp.
I have searched around for a bit but found nothing too concise.
To be clear this is the problem to do in one line:
//have this example associative array of data
$data = array(
'blue' => 43,
'red' => 87,
'purple' => 130,
'green' => 12,
'yellow' => 31
);
//and this array of keys to remove
$bad_keys = array(
'purple',
'yellow'
);
//some one liner here and then $data will only have the keys blue, red, green
$out =array_diff_key($data,array_flip($bad_keys));
All I did was look through the list of Array functions until I found the one I needed (_diff_key).
The solution is indeed the one provided by Niet the Dark Absol. I would like to provide another similar solution for anyone who is after similar thing, but this one uses a whitelist instead of a blacklist:
$whitelist = array( 'good_key1', 'good_key2', ... );
$output = array_intersect_key( $data, array_flip( $whitelist ) );
Which will preserve keys from $whitelist array and remove the rest.
This is a blacklisting function I created for associative arrays.
if(!function_exists('array_blacklist_assoc')){
/**
* Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays when using their values as keys.
* #param array $array1 The array to compare from
* #param array $array2 The array to compare against
* #return array $array2,... More arrays to compare against
*/
function array_blacklist_assoc(Array $array1, Array $array2) {
if(func_num_args() > 2){
$args = func_get_args();
array_shift($args);
$array2 = call_user_func_array('array_merge', $args);
}
return array_diff_key($array1, array_flip($array2));
}
}
$sanitized_data = array_blacklist_assoc($data, $bad_keys);
I have a two dimensional array like this
$FrstArr = Array(
[0]= array(
[0]=>101,
[1]=>ename1,
[2]=>1110
),
[1]= array(
[0]=>102,
[1]=>ename2,
[2]=>1111
),
[2]= array(
[0]=>103,
[1]=>ename3,
[2]=>1112
)
)
From this array I need to create one single dimensional array like this
$secondArr = array([0]=>1110,[1]=>1111,[2]=>1112);
With out using any loops how can I create $secondArr array using $FrstArr multidimensional array? Any php built in functionality is available for that?
$secondArr = array_map(function ($i) { return $i[2]; }, $FrstArr);
This loops as well, but behind the scenes.
$secondArr = array_map(
function ($item) { return $item[2]; },
$firstArr
);
Worth to mention, that this will also (internally) loop over the array.