From:
$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));
to:
array('A','B',..);
$output = array();
foreach ($arr as $array_piece) {
$output = array_merge($output, $array_piece);
}
return array_values($output);
On the other hand, if you want the first value from each array, what you want is...
$output = array();
foreach ($arr as $array_piece) {
$output[] = array_unshift($array_piece);
}
But I'm thinking you want the first one.
Relatively simple conversion by looping:
$newArray = array()
foreach ($arr as $a) {
foreach ($a as $key => $value) {
$newArray[] = $value;
}
}
Or, perhaps more elegantly:
function flatten($concatenation, $subArray) {
return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());
John's solution is also nice.
Something like this should work
<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));
$new_array = array();
foreach ($arr as $key => $value) {
$new_array = array_merge($new_array, array_values($value));
}
var_export($new_array);
?>
If you want all the values in each array inside your main array.
function collapse($input) {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf = array_merge($buf, collapse($i));
}
else $buf[] = $input;
return $buf;
}
Above is a modified unsplat function, which could also be used:
function unsplat($input, $delim="\t") {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf[] = unsplat($i, $delim);
}
else $buf[] = $input;
return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));
Related
I have two array i.e $arr1 and $arr2 where I want to find missing value of $arr1 which is not present in $arr2 without using function like array_diff(), count(), explode(), implode() etc. So, How can I do this? Please help me.
code:
<?php
$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');
$array = array_diff($arr1,$arr2);
print_r($arr2);
?>
First approach:-
$missingValuesArray = array();
foreach($arr1 as $arr){
if(!in_array($arr,$arr2)){
$missingValuesArray[] = $arr;
}
}
print_r($missingValuesArray);
Output:- https://3v4l.org/UBS9G
Second approach:-
$missingValuesArray = array();
foreach($arr1 as $arr){
$counter = 0;
foreach($arr2 as $ar){
if($arr != $ar){
$counter++;
}
}
if($counter == sizeof($arr2)){
$missingValuesArray[] = $arr;
}
}
print_r($missingValuesArray);
Output:- https://3v4l.org/Uu6Ob
Requirement can be achieved by :
$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');
$diff = array();
$diff = $arr1;
$arrayDiff = array();
foreach($arr1 AS $value) {
foreach($arr2 AS $val) {
if ($value == $val) {
$arrayDiff[] = $value;
continue;
}
}
}
foreach ($arrayDiff AS $k=>$v) {
if (($key = array_search($v, $diff)) !== false) {
unset($diff[$key]);
}
}
print_r($diff);
$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);
Is there a simple way to take a single-dimensional array and convert it to a multi-dimensional array based on the spaces, or any character(s), in the keys?
$arr['foo1'] = 'bar1';
$arr['foo2'] = 'bar2';
$arr['foo3 tier1' ] = 'bar3';
$arr['foo4 tier1' ] = 'bar4';
and turn it into
$arr['foo1'] = 'bar1';
$arr['foo2'] = 'bar2';
$arr['foo3']['tier1'] = 'bar3';
$arr['foo4']['tier1'] = 'bar4';
you can always do some sort of foreach loop
$newarr = array();
foreach ($arr as $key => $value) {
$output = explode(' ',$key,2);
if(count($output)) {
$newarr[$output[0]][$output[1]] = $value;
} else {
$newarr[$key] = $value;
}
}
That code will only work for one space but you can expand it to multiple spaces, something like
function pivot($arr,$delimeter) {
$return = array();
foreach ($arr as $key => $value) {
$output = explode($delimeter,$key,2);
if(count($output)) {
if(strpos($output[1],$delimeter) > 0) {
$return[$output[0]] = pivot(array($output[1]=>$value),$delimeter);
} else {
$return[$output[0]][$output[1]] = $value;
}
} else {
$return[$key] = $value;
}
}
return $return;
}
I have an array for example ("1:2","5:90","7:12",1:70,"29:60") Wherein ID and Qty are separated by a ':' (colon), what I want to do is when there's a duplicate of IDs the program will add the qty and return the new set of arrays so in the example it will become ("1:72","5:90","7:12","29:60").
Ex.2
("1:2","5:90","7:12","1:70","29:60","1:5")
becomes
("1:77","5:90","7:12","29:60").
<?php
$arr = array("1:2","5:90","7:12", "1:70","29:60");
$newArr = array();
foreach($arr as $key => $value) {
list($id, $quantity) = explode(':', $value);
if(isset($newArr[$id]))
$newArr[$id] += $quantity;
else
$newArr[$id] = $quantity;
}
foreach($newArr as $key => $value) {
$newArr[$key] = "$key:$value";
}
print_r($newArr);
Simple step by step:
$arr = array("1:2","5:90","7:12","1:70","29:60");
$tmp = array();
foreach($arr as $item)
{
list($id, $value) = explode(':', $item);
if (isset($tmp[$id]))
$tmp[$id] += $value;
else
$tmp[$id] = $value;
}
$arr = array();
foreach($tmp as $id => $value)
array_push($arr, $id . ':' . $value);
var_dump($arr);
Assuming the data format is an actual array, or you can parse it into one:
$data = array("1:2","5:90","7:12","1:70","29:60","1:5");
$values = array();
foreach ($data as $value) {
list($id, $qty) = explode(':', $value);
if (isset($values[$id])) {
$values[$id] += $qty;
} else {
$values[$id] = $qty;
}
}
foreach ($values as $id => &$qty) {
$qty = "$id:$qty";
}
$values = array_values($values);
Try to do like this
$array = array("1:2","5:90","7:12","1:70","29:60","1:5");
$result = array();
$sum = array();
foreach($array as $value)
{
list($k,$v) = explode(':',$value);
$sum[$k] += $v;
$result[$k] = $k.':'.$sum[$k];
}
unset($sum);
print_r($result);
Given an array, I would like a flattened version of the array keys. Each array key would need the 'path' of the array, to that point, appended with an underscore.
An example explains this best.
$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array("three"=>0)));
function answer($arr) {....}
the answer function would return this:
array("location","details_width","details_height","details_level_three");
UPDATE:
Here is the work in progress. It will accept an array and return the array keys, but with no depth:
function recursive_keys($input)
{
$output = array_keys($input);
foreach($input as $sub){
if(is_array($sub)){
$output = array_merge($output, recursive_keys($sub));
}
}
return $output;
}
$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$results = array();
foreach ($ritit as $leafValue) {
$path = array();
foreach (range(0, $ritit->getDepth()) as $depth) {
$path[] = $ritit->getSubIterator($depth)->key();
}
$results[] = join('_', $path);
}
function recursive_keys(array $array, array $path = array()) {
$result = array();
foreach ($array as $key => $val) {
$currentPath = array_merge($path, array($key));
if (is_array($val)) {
$result = array_merge($result, recursive_keys($val, $currentPath));
} else {
$result[] = join('_', $currentPath);
}
}
return $result;
}
Demo here: http://codepad.viper-7.com/WQ3UYI