how to append associative arrays into another array inside loop - php - php

I really hope you help me with this problem, I hope this make sence for you
- I have this pseudo example of foreach loop:
foreach_loop {
$k1 = GetKey1();
$v1 = GetValue1();
$k2 = GetKey2();
$v2 = GetValue2();
$k3 = GetKey3();
$v2 = GetValue3();
// now I put those keys and values in associative array called DataArr
$DataArr[$k1] = $v1;
$DataArr[$k2] = $v2;
$DataArr[$k3] = $v3;
}
now my question is, how do I create an array where each index of it contain an associative array created from that foreach loop and keep appending to itself like this:
$resultArr = array(
0 => "DataArr_from_loop1",
1 => "DataArr_from_loop2",
2 => "DataArr_from_loop3",
3 => "DataArr_from_loop4"
//...etc
)
and when I check for $resultArr[0] I should get an associative array like this:
array (size=3)
'k1' => string 'v1'
'k2' => string 'v2'
'k3' => string 'v3'
I really need your help, thank you in advance.

how about...
$resultArr = array();
foreach($whatever as $thing) {
$k1 = GetKey1();
$v1 = GetValue1();
$k2 = GetKey2();
$v2 = GetValue2();
$k3 = GetKey3();
$v2 = GetValue3();
// now I put those keys and values in associative array called DataArr
$DataArr = array();
$DataArr[$k1] = $v1;
$DataArr[$k2] = $v2;
$DataArr[$k3] = $v3;
$resultArr[] = $DataArr;
}

http://php.net/manual/en/function.array-push.php
int array_push ( array &$array , mixed $value1 [, mixed $... ] )
or
<?php
/**
* #desc array_push and removes elements from the beginning of the array until it is within limit
* #param array Array to push on to
* #param mixed Passed to array push as 2nd parameter
* #param int Limit (default = 10)
*
* #return array New array
*/
function array_push_limit($array,$add,$limit=10){
array_push($array, $add);
do {
array_shift($array);
$size=count($array);
} while($size > $limit);
return $array;
}
?>
----------
EXAMPLE:
----------
<?php
$array=array(1, -5, 23, -66, 33, 54, 3);
print_r(array_push_limit($array, "HELLO", 4));
?>
----------
OUTPUT:
----------
Array
(
[0] => 33
[1] => 54
[2] => 3
[3] => HELLO
)

Related

Insert into a PHP associative array with a specific key order [duplicate]

Let's imagine that we have two arrays:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
Now, I'd like to insert array('sample_key' => 'sample_value') after third element of each array. How can I do it?
array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);
This example:
$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);
gives:
Array
(
[zero] => 0
[one] => 1
[two] => 2
[my_key] => my_value
[three] => 3
)
For your first array, use array_splice():
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
array_splice($array_1, 3, 0, 'more');
print_r($array_1);
output:
Array(
[0] => zero
[1] => one
[2] => two
[3] => more
[4] => three
)
for the second one there is no order so you just have to do :
$array_2['more'] = '2.5';
print_r($array_2);
And sort the keys by whatever you want.
code:
function insertValueAtPosition($arr, $insertedArray, $position) {
$i = 0;
$new_array=[];
foreach ($arr as $key => $value) {
if ($i == $position) {
foreach ($insertedArray as $ikey => $ivalue) {
$new_array[$ikey] = $ivalue;
}
}
$new_array[$key] = $value;
$i++;
}
return $new_array;
}
example:
$array = ["A"=8, "K"=>3];
$insert_array = ["D"= 9];
insertValueAtPosition($array, $insert_array, $position=2);
// result ====> ["A"=>8, "D"=>9, "K"=>3];
May not really look perfect, but it works.
Here's a simple function that you could use. Just plug n play.
This is Insert By Index, Not By Value.
you can choose to pass the array, or use one that you already have declared.
Newer, shorter version:
function insert($array, $index, $val)
{
$size = count($array); //because I am going to use this more than one time
if (!is_int($index) || $index < 0 || $index > $size)
{
return -1;
}
else
{
$temp = array_slice($array, 0, $index);
$temp[] = $val;
return array_merge($temp, array_slice($array, $index, $size));
}
}
Older, longer version:
function insert($array, $index, $val) { //function decleration
$temp = array(); // this temp array will hold the value
$size = count($array); //because I am going to use this more than one time
// Validation -- validate if index value is proper (you can omit this part)
if (!is_int($index) || $index < 0 || $index > $size) {
echo "Error: Wrong index at Insert. Index: " . $index . " Current Size: " . $size;
echo "<br/>";
return false;
}
//here is the actual insertion code
//slice part of the array from 0 to insertion index
$temp = array_slice($array, 0, $index);//e.g index=5, then slice will result elements [0-4]
//add the value at the end of the temp array// at the insertion index e.g 5
array_push($temp, $val);
//reconnect the remaining part of the array to the current temp
$temp = array_merge($temp, array_slice($array, $index, $size));
$array = $temp;//swap// no need for this if you pass the array cuz you can simply return $temp, but, if u r using a class array for example, this is useful.
return $array; // you can return $temp instead if you don't use class array
}
Usage example:
//1
$result = insert(array(1,2,3,4,5),0, 0);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
//2
$result = insert(array(1,2,3,4,5),2, "a");
echo "<pre>";
print_r($result);
echo "</pre>";
//3
$result = insert(array(1,2,3,4,5) ,4, "b");
echo "<pre>";
print_r($result);
echo "</pre>";
//4
$result = insert(array(1,2,3,4,5),5, 6);
echo "<pre>";
echo "<br/>";
print_r($result);
echo "</pre>";
Expected result:
//1
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
//2
Array
(
[0] => 1
[1] => 2
[2] => a
[3] => 3
[4] => 4
[5] => 5
)
//3
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => b
[5] => 5
)
//4
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');
$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));
This function supports:
both numeric and assoc keys
insert before or after the founded key
append to the end of array if key isn't founded
function insert_into_array( $array, $search_key, $insert_key, $insert_value, $insert_after_founded_key = true, $append_if_not_found = false ) {
$new_array = array();
foreach( $array as $key => $value ){
// INSERT BEFORE THE CURRENT KEY?
// ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT BEFORE THAT FOUNDED KEY
if( $key === $search_key && ! $insert_after_founded_key )
$new_array[ $insert_key ] = $insert_value;
// COPY THE CURRENT KEY/VALUE FROM OLD ARRAY TO A NEW ARRAY
$new_array[ $key ] = $value;
// INSERT AFTER THE CURRENT KEY?
// ONLY IF CURRENT KEY IS THE KEY WE ARE SEARCHING FOR, AND WE WANT TO INSERT AFTER THAT FOUNDED KEY
if( $key === $search_key && $insert_after_founded_key )
$new_array[ $insert_key ] = $insert_value;
}
// APPEND IF KEY ISNT FOUNDED
if( $append_if_not_found && count( $array ) == count( $new_array ) )
$new_array[ $insert_key ] = $insert_value;
return $new_array;
}
USAGE:
$array1 = array(
0 => 'zero',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four'
);
$array2 = array(
'zero' => '# 0',
'one' => '# 1',
'two' => '# 2',
'three' => '# 3',
'four' => '# 4'
);
$array3 = array(
0 => 'zero',
1 => 'one',
64 => '64',
3 => 'three',
4 => 'four'
);
// INSERT AFTER WITH NUMERIC KEYS
print_r( insert_into_array( $array1, 3, 'three+', 'three+ value') );
// INSERT AFTER WITH ASSOC KEYS
print_r( insert_into_array( $array2, 'three', 'three+', 'three+ value') );
// INSERT BEFORE
print_r( insert_into_array( $array3, 64, 'before-64', 'before-64 value', false) );
// APPEND IF SEARCH KEY ISNT FOUNDED
print_r( insert_into_array( $array3, 'undefined assoc key', 'new key', 'new value', true, true) );
RESULTS:
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[three+] => three+ value
[4] => four
)
Array
(
[zero] => # 0
[one] => # 1
[two] => # 2
[three] => # 3
[three+] => three+ value
[four] => # 4
)
Array
(
[0] => zero
[1] => one
[before-64] => before-64 value
[64] => 64
[3] => three
[4] => four
)
Array
(
[0] => zero
[1] => one
[64] => 64
[3] => three
[4] => four
[new key] => new value
)
Simplest solution, if you want to insert (an element or array) after a certain key:
function array_splice_after_key($array, $key, $array_to_insert)
{
$key_pos = array_search($key, array_keys($array));
if($key_pos !== false){
$key_pos++;
$second_array = array_splice($array, $key_pos);
$array = array_merge($array, $array_to_insert, $second_array);
}
return $array;
}
So, if you have:
$array = [
'one' => 1,
'three' => 3
];
$array_to_insert = ['two' => 2];
And execute:
$result_array = array_splice_after_key($array, 'one', $array_to_insert);
You'll have:
Array (
['one'] => 1
['two'] => 2
['three'] => 3
)
I recently wrote a function to do something similar to what it sounds like you're attempting, it's a similar approach to clasvdb's answer.
function magic_insert($index,$value,$input_array ) {
if (isset($input_array[$index])) {
$output_array = array($index=>$value);
foreach($input_array as $k=>$v) {
if ($k<$index) {
$output_array[$k] = $v;
} else {
if (isset($output_array[$k]) ) {
$output_array[$k+1] = $v;
} else {
$output_array[$k] = $v;
}
}
}
} else {
$output_array = $input_array;
$output_array[$index] = $value;
}
ksort($output_array);
return $output_array;
}
Basically it inserts at a specific point, but avoids overwriting by shifting all items down.
Using array_splice instead of array_slice gives one less function call.
$toto = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3'
);
$ret = array_splice($toto, 3 );
$toto = $toto + array("my_key" => "my_value") + $ret;
print_r($toto);
If you don't know that you want to insert it at position #3, but you know the key that you want to insert it after, I cooked up this little function after seeing this question.
/**
* Inserts any number of scalars or arrays at the point
* in the haystack immediately after the search key ($needle) was found,
* or at the end if the needle is not found or not supplied.
* Modifies $haystack in place.
* #param array &$haystack the associative array to search. This will be modified by the function
* #param string $needle the key to search for
* #param mixed $stuff one or more arrays or scalars to be inserted into $haystack
* #return int the index at which $needle was found
*/
function array_insert_after(&$haystack, $needle = '', $stuff){
if (! is_array($haystack) ) return $haystack;
$new_array = array();
for ($i = 2; $i < func_num_args(); ++$i){
$arg = func_get_arg($i);
if (is_array($arg)) $new_array = array_merge($new_array, $arg);
else $new_array[] = $arg;
}
$i = 0;
foreach($haystack as $key => $value){
++$i;
if ($key == $needle) break;
}
$haystack = array_merge(array_slice($haystack, 0, $i, true), $new_array, array_slice($haystack, $i, null, true));
return $i;
}
Here's a codepad fiddle to see it in action: http://codepad.org/5WlKFKfz
Note: array_splice() would have been a lot more efficient than array_merge(array_slice()) but then the keys of your inserted arrays would have been lost. Sigh.
Cleaner approach (based on fluidity of use and less code).
/**
* Insert data at position given the target key.
*
* #param array $array
* #param mixed $target_key
* #param mixed $insert_key
* #param mixed $insert_val
* #param bool $insert_after
* #param bool $append_on_fail
* #param array $out
* #return array
*/
function array_insert(
array $array,
$target_key,
$insert_key,
$insert_val = null,
$insert_after = true,
$append_on_fail = false,
$out = [])
{
foreach ($array as $key => $value) {
if ($insert_after) $out[$key] = $value;
if ($key == $target_key) $out[$insert_key] = $insert_val;
if (!$insert_after) $out[$key] = $value;
}
if (!isset($array[$target_key]) && $append_on_fail) {
$out[$insert_key] = $insert_val;
}
return $out;
}
Usage:
$colors = [
'blue' => 'Blue',
'green' => 'Green',
'orange' => 'Orange',
];
$colors = array_insert($colors, 'blue', 'pink', 'Pink');
die(var_dump($colors));
This is an old question, but I posted a comment in 2014 and frequently come back to this. I thought I would leave a full answer. This isn't the shortest solution but it is quite easy to understand.
Insert a new value into an associative array, at a numbered position, preserving keys, and preserving order.
$columns = array(
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
'count' => 'Number of posts'
);
$columns = array_merge(
array_slice( $columns, 0, 3, true ), // The first 3 items from the old array
array( 'subscribed' => 'Subscribed' ), // New value to add after the 3rd item
array_slice( $columns, 3, null, true ) // Other items after the 3rd
);
print_r( $columns );
/*
Array (
[id] => ID
[name] => Name
[email] => Email
[subscribed] => Subscribed
[count] => Number of posts
)
*/
I do that as
$slightly_damaged = array_merge(
array_slice($slightly_damaged, 0, 4, true) + ["4" => "0.0"],
array_slice($slightly_damaged, 4, count($slightly_damaged) - 4, true)
);
This is another solution in PHP 7.1
/**
* #param array $input Input array to add items to
* #param array $items Items to insert (as an array)
* #param int $position Position to inject items from (starts from 0)
*
* #return array
*/
function arrayInject( array $input, array $items, int $position ): array
{
if (0 >= $position) {
return array_merge($items, $input);
}
if ($position >= count($input)) {
return array_merge($input, $items);
}
return array_merge(
array_slice($input, 0, $position, true),
$items,
array_slice($input, $position, null, true)
);
}
I just created an ArrayHelper class that would make this very easy for numeric indexes.
class ArrayHelper
{
/*
Inserts a value at the given position or throws an exception if
the position is out of range.
This function will push the current values up in index. ex. if
you insert at index 1 then the previous value at index 1 will
be pushed to index 2 and so on.
$pos: The position where the inserted value should be placed.
Starts at 0.
*/
public static function insertValueAtPos(array &$array, $pos, $value) {
$maxIndex = count($array)-1;
if ($pos === 0) {
array_unshift($array, $value);
} elseif (($pos > 0) && ($pos <= $maxIndex)) {
$firstHalf = array_slice($array, 0, $pos);
$secondHalf = array_slice($array, $pos);
$array = array_merge($firstHalf, array($value), $secondHalf);
} else {
throw new IndexOutOfBoundsException();
}
}
}
Example:
$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);
Beginning $array:
Array (
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
Result:
Array (
[0] => a
[1] => b
[2] => c
[3] => insert
[4] => d
[5] => e
)
This is better method how insert item to array on some position.
function arrayInsert($array, $item, $position)
{
$begin = array_slice($array, 0, $position);
array_push($begin, $item);
$end = array_slice($array, $position);
$resultArray = array_merge($begin, $end);
return $resultArray;
}
I needed something that could do an insert before, replace, after the key; and add at the start or end of the array if target key is not found. Default is to insert after the key.
New Function
/**
* Insert element into an array at a specific key.
*
* #param array $input_array
* The original array.
* #param array $insert
* The element that is getting inserted; array(key => value).
* #param string $target_key
* The key name.
* #param int $location
* 1 is after, 0 is replace, -1 is before.
*
* #return array
* The new array with the element merged in.
*/
function insert_into_array_at_key(array $input_array, array $insert, $target_key, $location = 1) {
$output = array();
$new_value = reset($insert);
$new_key = key($insert);
foreach ($input_array as $key => $value) {
if ($key === $target_key) {
// Insert before.
if ($location == -1) {
$output[$new_key] = $new_value;
$output[$key] = $value;
}
// Replace.
if ($location == 0) {
$output[$new_key] = $new_value;
}
// After.
if ($location == 1) {
$output[$key] = $value;
$output[$new_key] = $new_value;
}
}
else {
// Pick next key if there is an number collision.
if (is_numeric($key)) {
while (isset($output[$key])) {
$key++;
}
}
$output[$key] = $value;
}
}
// Add to array if not found.
if (!isset($output[$new_key])) {
// Before everything.
if ($location == -1) {
$output = $insert + $output;
}
// After everything.
if ($location == 1) {
$output[$new_key] = $new_value;
}
}
return $output;
}
Input code
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$array_1 = insert_into_array_at_key($array_1, array('sample_key' => 'sample_value'), 2, 1);
print_r($array_1);
$array_2 = insert_into_array_at_key($array_2, array('sample_key' => 'sample_value'), 'two', 1);
print_r($array_2);
Output
Array
(
[0] => zero
[1] => one
[2] => two
[sample_key] => sample_value
[3] => three
)
Array
(
[zero] => 0
[one] => 1
[two] => 2
[sample_key] => sample_value
[three] => 3
)
Very simple 2 string answer to your question:
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
At first you insert anything to your third element with array_splice and then assign a value to this element:
array_splice($array_1, 3, 0 , true);
$array_1[3] = array('sample_key' => 'sample_value');
Not as concrete as the answer of Artefacto, but based in his suggestion of using array_slice(), I wrote the next function:
function arrayInsert($target, $byKey, $byOffset, $valuesToInsert, $afterKey) {
if (isset($byKey)) {
if (is_numeric($byKey)) $byKey = (int)floor($byKey);
$offset = 0;
foreach ($target as $key => $value) {
if ($key === $byKey) break;
$offset++;
}
if ($afterKey) $offset++;
} else {
$offset = $byOffset;
}
$targetLength = count($target);
$targetA = array_slice($target, 0, $offset, true);
$targetB = array_slice($target, $offset, $targetLength, true);
return array_merge($targetA, $valuesToInsert, $targetB);
}
Features:
Inserting one or mĂșltiple values
Inserting key value pair(s)
Inserting before/after the key, or by offset
Usage examples:
$target = [
'banana' => 12,
'potatoe' => 6,
'watermelon' => 8,
'apple' => 7,
2 => 21,
'pear' => 6
];
// Values must be nested in an array
$insertValues = [
'orange' => 0,
'lemon' => 3,
3
];
// By key
// Third parameter is not applicable
// Insert after 2 (before 'pear')
var_dump(arrayInsert($target, 2, null, $valuesToInsert, true));
// Insert before 'watermelon'
var_dump(arrayInsert($target, 'watermelon', null, $valuesToInsert, false));
// By offset
// Second and last parameter are not applicable
// Insert in position 2 (zero based i.e. before 'watermelon')
var_dump(arrayInsert($target, null, 2, $valuesToInsert, null));
In case you are just looking to insert an item into an array at a certain position (based on #clausvdb answer):
function array_insert($arr, $insert, $position) {
$i = 0;
$ret = array();
foreach ($arr as $key => $value) {
if ($i == $position) {
$ret[] = $insert;
}
$ret[] = $value;
$i++;
}
return $ret;
}
Here is my version:
/**
*
* Insert an element after an index in an array
* #param array $array
* #param string|int $key
* #param mixed $value
* #param string|int $offset
* #return mixed
*/
function array_splice_associative($array, $key, $value, $offset) {
if (!is_array($array)) {
return $array;
}
if (array_key_exists($key, $array)) {
unset($array[$key]);
}
$return = array();
$inserted = false;
foreach ($array as $k => $v) {
$return[$k] = $v;
if ($k == $offset && !$inserted) {
$return[$key] = $value;
$inserted = true;
}
}
if (!$inserted) {
$return[$key] = $value;
}
return $return;
}
try this one ===
$key_pos=0;
$a1=array("a"=>"red", "b"=>"green", "c"=>"blue", "d"=>"yellow");
$arrkey=array_keys($a1);
array_walk($arrkey,function($val,$key) use(&$key_pos) {
if($val=='b')
{
$key_pos=$key;
}
});
$a2=array("e"=>"purple");
$newArray = array_slice($a1, 0, $key_pos, true) + $a2 +
array_slice($a1, $key_pos, NULL, true);
print_r($newArray);
Output
Array (
[a] => red
[e] => purple
[b] => green
[c] => blue
[d] => yellow )
This can be done by array.splice(). Please note array_splice or array_merge doesn't preserve keys for associative arrays. So array_slice is used and '+' operator is used for concatenating the two arrays.
More details here
$array_1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array_2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$index = 2;
$finalArray = array_slice($array_1, 0, $index, true) +
$array2 +
array_slice($array_2, $index, NULL, true);
print_r($finalArray);
/*
Array
(
[0] => zero
[1] => one
[10] => grapes
[z] => mangoes
[two] => 2
[three] => 3
)
*/
I've created a function (PHP 8.1), which allows you to insert items to associative or numeric arrays:
function insertItemsToPosition(array $array, string|int $insertAfterPosition, array $itemsToAdd): array
{
$insertAfterIndex = array_search($insertAfterPosition, array_keys($array), true);
if ($insertAfterIndex === false) {
throw new \UnexpectedValueException(sprintf('You try to insert items to an array after the key "%s", but this key is not existing in given array. Available keys are: %s', $insertAfterPosition, implode(', ', array_keys($array))));
}
$itemsBefore = array_slice($array, 0, $insertAfterIndex + 1);
$itemsAfter = array_slice($array, $insertAfterIndex + 1);
return $itemsBefore + $itemsToAdd + $itemsAfter;
}
You can insert elements during a foreach loop, since this loop works on a copy of the original array, but you have to keep track of the number of inserted lines (I call this "bloat" in this code):
$bloat=0;
foreach ($Lines as $n=>$Line)
{
if (MustInsertLineHere($Line))
{
array_splice($Lines,$n+$bloat,0,"string to insert");
++$bloat;
}
}
Obviously, you can generalize this "bloat" idea to handle arbitrary insertions and deletions during the foreach loop.

Flatten 2d array and cast all string values to int

How should I make this array value that is in string form
Array
(
[0] => ["1","2"]
[1] => ["5"]
)
into int form
Array
(
[0] => 1
[1] => 2
[2] => 5
)
Is it complicated? Anyone can help?
you can use array_map to parse string to int and array_reduce with array_merge to join the arrays
$data = Array(["1","2"],["5"]);
$result = array_map('intval', array_reduce($data, 'array_merge', array()));
print_r($result);
Try this:
$array = [
["1", "2"],
["5"],
];
$newArray = [];
foreach ($array as $rowArr) {
foreach ($rowArr as $str) {
$newArray[] = intval($str);
}
}
var_dump($newArray);
This returns:
array (size=3)
0 => int 1
1 => int 2
2 => int 5
This works by iterating $array, then iterating $array's child elements ($rowArr) and adding each element to $newArray after running intval on it.
Use array_reduce (https://3v4l.org/H4eIV)
$a = Array
(
0=> ["1","2"],
1=> ["5"]
);
$r = array_reduce($a, 'array_merge', array());
var_export($r);
Result:
array (
0 => '1',
1 => '2',
2 => '5',
)
You only need to loop through the two layers of your array.
$input=[["1","2"],["5"]];
foreach($input as $a){
foreach($a as $v){
$result[]=+$v; // make integer
}
}
var_export($result);
Another way: create a closure that casts variables to ints and appends them to an array.
$appendInt = function($x) use (&$result) { $result[] = (int) $x; };
// reference to result array^ append to result^ ^cast to int
Apply it to every element of your multidimensional array with array_walk_recursive.
array_walk_recursive($your_array, $appendInt);
The flat array of ints will be in the $result variable.

Merging arrays recursively PHP

I am using this function two merge recursively arrays:
function array_merge_recursive_distinct(array &$array1, array &$array2) {
$merged = $array1;
foreach($array2 as $key => &$value) {
if(is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
For using this function I am doing the following steps:
Declare an empty array $outArray = array();
Doing a while loop where I collect the information I need
During the while loop I call the array_merge_recursive_distinct function to fill the empty array recursively
However the final array contains only the last information it was gathered during the last while loop. I have tried to find a solution but I haven't succeed until now. What Am I doing wrong?
The recursive function takes all the info during the while loops (I have printed the input arrays in the recursive function) but it seems like it overwrites the merged array over and over again.
Thanks
CakePHP have a nice class called Hash, it implements a method called merge() who does exactly what you need
/**
* This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
*
* The difference between this method and the built-in ones, is that if an array key contains another array, then
* Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for
* keys that contain scalar values (unlike `array_merge_recursive`).
*
* Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
*
* #param array $data Array to be merged
* #param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
* #return array Merged array
* #link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
*/
function merge_arrays_recursivelly(array $data, $merge) { // I changed the function name from merge to merge_arrays_recursivelly
$args = array_slice(func_get_args(), 1);
$return = $data;
foreach ($args as &$curArg) {
$stack[] = array((array) $curArg, &$return);
}
unset($curArg);
while (!empty($stack)) {
foreach ($stack as $curKey => &$curMerge) {
foreach ($curMerge[0] as $key => &$val) {
if (!empty($curMerge[1][$key]) && (array) $curMerge[1][$key] === $curMerge[1][$key] && (array) $val === $val) {
$stack[] = array(&$val, &$curMerge[1][$key]);
} elseif ((int) $key === $key && isset($curMerge[1][$key])) {
$curMerge[1][] = $val;
} else {
$curMerge[1][$key] = $val;
}
}
unset($stack[$curKey]);
}
unset($curMerge);
}
return $return;
}
https://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
Hash::merge source code
Perhaps something like this might be handy.
function array_merge_recursive_distinct(array &$array1, array &$array2) {
$merged = array_merge($array1,$array2);
asort($merged);
$merged = array_values(array_unique($merged));
return $merged;
}
$array1 = [];
$array2 = [1,2,3,4,5];
print_r(array_merge_recursive_distinct($array1,$array2));
$array1 = [1,2,3,6,12,19];
$array2 = [1,2,3,4,5];
print_r(array_merge_recursive_distinct($array1,$array2));
// output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 12
[7] => 19
)
Test it on PHP Sandbox

manipulate a 2D array in PHP

I have a 2 Dimentional array in php as follow :
Array
(
[0] => Array
(
[0] => 10
[1] =>
)
[1] => Array
(
[0] => 67
[1] =>
)
[2] => Array
(
[0] => 67
[1] => 50
)
)
I want to manipulate it as follow:
Array
(
[0] => Array
(
[0] => 10
[1] => 67
[2] => 67
)
[1] => Array
(
[0] =>
[1] =>
[2] => 50
)
)
Means I want to take first elements of all inner arrays in one array and 2nd element in another array.
How can I manipulate this. Plz help
You can array_map() instead of loop. Example:
$newArr[] = array_map(function($v){return $v[0];},$arr);
$newArr[] = array_map(function($v){return $v[1];},$arr);
Or can use array_column() if your PHP 5.5+
$newArr[] = array_column($arr, 0);
$newArr[] = array_column($arr, 1);
print '<pre>';
print_r($newArr);
print '</pre>';
Just run the following script:
$array1 = array();
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j < count($array1[$i]); $j++) {
$array2[$j][$i] = $array1[$i][$j];
}
}
Here's a general solution that works regardless of how many items you have in the array and the sub-arrays:
// Set up an array for testing
$my_array = array( array(10, null), array(67, null), array(67, 50));
/**
* Our magic function; takes an array and produces a consolidated array like you requested
* #param array $data The unprocessed data
* #return array
*/
function consolidate_sub_arrays($data)
{
/**
* The return array
* #var array $return_array
*/
$return_array = array();
// Loop over the existing array
foreach ($data as $outer) {
// Loop over the inner arrays (sub-arrays)
foreach($outer as $key => $val) {
// Set up a new sub-array in the return array, if it doesn't exist
if (!array_key_exists($key, $return_array)) {
$return_array[$key] = array();
}
// Add the value to the appropriate sub-array of the return array
$return_array[$key][] = $val;
}
}
// Done!
return $return_array;
}
// Just to verify it works; delete this in production
print_r(consolidate_sub_arrays($my_array));
You need to loop over the initial array and create a new array in the format you want it.
$new_array = array();
foreach ($input_array as $in ) {
$new_array[0][] = $in[0];
$new_array[1][] = $in[1];
}
print_r($new_array);

Split array into chunks using separator

Hope everyone is doing well...
I am looking for something similar to array_chunk() but using an empty value as the separator?
I have -
Array
(
[0] => /some/path:
[1] => file.csv
[2] => file.dat
[3] =>
[4] => /some/other/path:
[5] => file.csv
[6] => file.csv.gz
[7] => file.dat
[8] =>
[9] => /some/other/other/path:
[10] => file.csv
[11] => file.dat
)
And would like to achieve -
Array
(
[0] => Array
(
[0] => /some/path:
[1] => file.csv
[2] => file.dat
)
[1] => Array
(
[0] => /some/other/path:
[1] => file.csv
[2] => file.csv.gz
[3] => file.dat
)
[2] => Array
(
[0] => /some/other/other/path:
[1] => file.csv
[2] => file.dat
)
)
Now I cant just chunk on every 3 as you can see some locations will have more than 1 file.
I can achieve via loop and counter but I figured there would be a cleaner method?
Thanks
Best way I can think of is this loop which I think is pretty clean:
/**
* #param array $inputArr The array you wish to split.
* #param string $splitStr The string you wish to split by.
*
* #return array
*/
function split_arrays($inputArr, $splitStr) {
$outputArr = array();
$i = 0;
foreach ($inputArr as $data) {
if ($data == $splitStr) {
$i++;
continue;
}
$outputArr[$i][] = $data;
}
return $outputArr;
}
The other way I thought of also uses loops but is not as clean. It searches for the index of the next split string and breaks off that chunk.
/**
* #param array $inputArr The array you wish to split.
* #param string $splitStr The string you wish to split by.
*
* #return array
*/
function split_arrays2($inputArr,$splitStr) {
$outputArr = array(); $i=0;
while(count($inputArr)) {
$index = array_search($splitStr,$inputArr)
if($index === false) $index = count($inputArr);
$outputArr[$i++] = array_slice($inputArr,0,$index);
$inputArr = array_slice($inputArr,$index+1);
}
return $outputArr;
}
If and only if you are using a string for the split string which is not ever going to show up inside the middle of the other strings (space may or may not be the case for this) then I agree with the others that implode and explode are much simpler. In your case:
/**
* #param array $inputArr The array you wish to split.
* #param string $splitStr The string you wish to split by.
*
* #return array
*/
function split_arrays3($inputArr,$splitStr) {
$outputArr = array(); $i=0;
$str = implode("|",$inputArr);
$arr = explode("|$splitStr|");
foreach($arr as $i=>$string)
$outputArr[$i] = explode("|",$string);
return $outputArr;
}
$res = array();
foreach(explode("\n\n", implode("\n", $arr)) as $k => $v) {
$res[$k] = explode("\n", $v);
}
$res will contains the array you want.
Do you have two characters that will not occur in the array string for sure?
If so, suppose they are # and ;
We'll use combination of implode and explode
Then:
$arrstring = implode(';',$old_array); // Split via ; spearators
$arrstring = str_replace(';;','#',$arrstring); // If two ;; then mark end of array as #
$new_pre_array = explode('#',$arrstring); // Outer array
// Inner array
foreach($new_pre_array as $key => $entry) {
$temp_sub_array = explode(';',$entry);
$new_pre_array[$key] = $temp_sub_array;
}
return $new_pre_array;
Reference:
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
$chunked = chunkArray($your_array);
function chunkArray($array){
$return = array();
$index = 0;
foreach($array as $ar){
if($ar == "" or $ar == null){
$index++;
}
else{
$return[$index][] = $ar;
}
}
return $return;
}
I was opting to first locate at which places the array $array has to be splitted:
$splitAt = array_keys($array, '', TRUE);
This actually is the most magic. The array_splice function then can be used to get the chunks from the input array, only a temporary variable, I named it $last:
$last = 0;
is used to keep track because the length is not the position. Those $splitAt are then used to be inserted into the
$result = array();
$result array:
foreach($splitAt as $pos) {
$result[] = array_splice($array, 0, $pos - $last);
unset($array[0]);
$last += $pos + 1;
}
The leftover chunk from the array is then added as last element:
$result[] = $array;
And that's it. The full Example (Demo):
/**
* explode array by delimiter
*
* #param mixed $delimiter
* #param array $array
* #return array
*/
function array_explode($delimiter, array $array)
{
$splitAt = array_keys($array, $delimiter, TRUE);
$last = 0;
$result = array();
foreach ($splitAt as $pos) {
$result[] = array_splice($array, 0, $pos - $last);
$array && unset($array[0]);
$last += $pos + 1;
}
$result[] = $array;
return $result;
}
# Usage:
var_dump(array_explode('', $array));
I named the function array_explode because it works like explode on strings but for arrays.
The second option I see (and which might be preferrable) is to loop over the array and process it according to it's value: Either add to the current element or add the current to it:
/**
* explode array by delimiter
*
* #param mixed $delimiter
* #param array $array
* #return array
*/
function array_explode($delimiter, array $array)
{
$result[] = &$current;
foreach($array as $value) {
if ($value === $delimiter) {
unset($current);
$result[] = &$current;
continue;
}
$current[] = $value;
}
return $result;
}

Categories