How to concatenate two Array keys? - php

I would like to know if there is a way to convert two Array keys into one Array key?
As an example the Array would look like:
[0] => '12345'
[1] => 'New'
[2] => 'York'
how can I combine [1] => 'New' and [2] => 'York' into [1] => 'New York'?
All I was found is array_merge that combines two Arrays. Even on how to concaternate two Array keys I could not find anything.
Thanks alot.

You can try :
$data = array(12345,"New","York");
echo concat($data, array(1,2)); //New York
//or
$data = array(12345,"New","York");
print_r(concatArray($data, array(1,2)));
Output
Array
(
[0] => 12345
[1] => New York
)
Function Used
function concat($array, $keys , $glue = " ") {
$values = array_intersect_key($array, array_flip($keys));
return implode($glue, $values);
}
function concatArray($array, $keys, $glue = " ") {
$last = null;
foreach ( $array as $key => &$value ) {
if (in_array($key, $keys)) {
if ($last === null) {
$last = $key;
continue;
}
$array[$last] .= $glue . $value;
unset($array[$key]);
}
}
return $array;
}

Here's a hint ;)
$new = $array[1] . ' ' . $array[2];
$array[1] = $new;
unset($array[2]);

Related

Map array with initial letter in PHP

I wish to group a word list in an array with the initial letter.
function alpha($str) {
$result[substr($str,0,1)] = $str;
return $result;
}
$a = ['abc','cde','frtg','acf'];
$b = array_map('alpha', $a);
print_r($b);
What I need:
Array
(
[a] => abc,acf
[c] => cde
[f] => frtg
)
What I get:
Array
(
[0] => Array
(
[a] => abc
)
[1] => Array
(
[c] => cde
)
[2] => Array
(
[f] => frtg
)
[3] => Array
(
[a] => acf
)
)
How about that :
$answer = [];
$a = ['abc','cde','frtg','acf'];
foreach($a as $word){
$key = substr($word,0,1);
if (isset($answer[$key])){
$answer[$key] .= "," . $word;
} else {
$answer[$key] = $word;
}
}
Just add a variable $c and loop over arrays of array using two foreach and group by alphabet...
function alpha($str) {
$result[substr($str,0,1)] = $str;
return $result;
}
$a = ['abc','cde','frtg','acf'];
$b = array_map('alpha', $a);
#print_r($b);
$c = [];
foreach ($b as $key => $values) {
foreach ($values as $key => $value) {
if(!isset($c[$key])){
$c[$key]=$value;
}else{
$c[$key].= "," . $value;
}
}
}
echo "<PRE>";
print_r($c);
Outupt:
Array
(
[a] => abc,acf
[c] => cde
[f] => frtg
)
The function array_map maps to the original indexes but you want new indexes and an altered array, if there are more values with the same initial character. Therefore array_map don't work for you. You could create your new array this way:
$a = ['abc','cde','frtg','acf'];
$b = Array();
$c = Array();
foreach( $a as $v )
{
// multidimensional array
$b[substr($v,0,1)][] = $v;
// comma separated string
$c[substr($v,0,1)] = (isset($c[substr($v,0,1)])) ?
$c[substr($v,0,1)].",$v" : $v;
}
If the first character can also be multibyte Unicode such as ° or €, mb_substr() must be used! Solution with foreach:
$result = [];
$a = ['abc','€de','frtg','acf'];
foreach($a as $word){
$key = mb_substr($word,0,1);
$result[$key] = array_key_exists($key,$result)
? ($result[$key].",".$word)
: $word
;
}
Solution with array_reduce():
$result = array_reduce($a,function($carry,$item){
$key = mb_substr($item,0,1);
$carry[$key] = array_key_exists($key,$carry) ? ($carry[$key].",".$item) : $item;
return $carry;
},[]);
var_export($result);
Output:
array (
'a' => 'abc,acf',
'€' => '€de',
'f' => 'frtg',
)
I think your intention is to store each word into arrays according to its first letter. In this case, the multidimensional array is the right choice.
$array = ['abc','cde','frtg','acf'];
$new_array = array();
foreach($array as $v){
$letter = substr($v,0,1);
if(!isset($new_array[$letter])) {$new_array[$letter] = array();}
array_push($new_array[$letter], $v);
}
print_r($new_array);

Convert a one dimensional array to two dimensional array

I have an array, whose structure is basically like this:
array('id,"1"', 'name,"abcd"', 'age,"30"')
I want to convert it into a two dimensional array, which has each element as key -> value:
array(array(id,1),array(name,abcd),array(age,30))
Any advice would be appreciated!
I tried this code:
foreach ($datatest as $lines => $value){
$tok = explode(',',$value);
$arrayoutput[$tok[0]][$tok[1]] = $value;
}
but it didn't work.
Assuming you want to remove all quotation marks as per your question:
$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}
You can do something like this:
$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
$temp = explode("," $first_array);
$b[$temp[0]] = $b[$temp[1]];
}
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
$val[] = array($aa);
}
print_r($val);
Output:
Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )
With array_map function:
$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
list($k,$v) = explode(',', $v);
return [$k => $v];
}, $arr);
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => "1"
)
[1] => Array
(
[name] => "abcd"
)
[2] => Array
(
[age] => "30"
)
)

Implode array joining only similar key?

I want to implode this array to make a string with all keys = 'Palabra'. How can this be done? (the output should be: 'juana es')
Array
(
[0] => Array
(
[Palabra] => juana
)
[1] => Array
(
[Palabra] => es
[0] => Array
(
[Raiz] => ser
[Tipo] => verbo
[Tipo2] => verbo1
)
)
)
function foo( $needly, $array ) {
$results = array();
foreach ( $array as $key => $value ) {
if ( is_array( $value ) ) {
$results = array_merge($results, foo( $needly, $value ));
} else if ( $key == $needly ) {
$results[] = $value;
}
}
return $results;
}
echo implode( " ", foo( "Palabra", $your_array ) );
I ended using the foreach for lack of a better solution:
foreach ($array as $key => $palabra) {
$newArray[] = $array[$key]["Palabra"];
}
$string = implode(' ', $newArray);
I think the simplest solution is with array_walk_recursive.
<?php
$arr = array(
array(
'Palabra' => 'juana',
),
array(
'Palabra' => 'es',
array(
'Raiz' => 'ser',
'Tipo' => 'verbo',
'Tipo2' => 'verbo1',
),
),
);
$str = array();
array_walk_recursive($arr, function($value, $key) use(&$str) {
if ($key == 'Palabra') {
$str[] = $value;
}
});
$str = implode(' ', $str);
echo "$str\n";
The function passed in is called for each key-value pair in the array and any subarrays. Here we append any values with a matching key to an array and then implode the array to get a string.

php multidimensional array from known key values

I have a collection of keys in this massive flat single array I would like to basically expand that array into a multidimensional one organized by keys - here is an example:
'invoice/products/data/item1'
'invoice/products/data/item2'
'invoice/products/data/item2'
=>
'invoice'=>'products'=>array('item1','item2','item3')
how can I do this - the length of the above strings are variable...
Thanks!
$src = array(
'invoice/products/data/item1',
'invoice/products/data/item2',
'invoice/products/data/item2',
'foo/bar/baz',
'aaa/bbb'
);
function rsplit(&$v, $w)
{
list($first, $tail) = explode('/', $w, 2);
if(empty($tail))
{
$v[] = $first;
return $v;
}
$v[$first] = rsplit($v[$first], $tail);
return $v;
}
$result = array_reduce($src, "rsplit");
print_r($result);
Output is:
Array (
[invoice] => Array
(
[products] => Array
(
[data] => Array
(
[0] => item1
[1] => item2
[2] => item2
)
)
)
[foo] => Array
(
[bar] => Array
(
[0] => baz
)
)
[aaa] => Array
(
[0] => bbb
)
)
Something along these lines: (Didn't test it though!) Works now ;)
$data = array();
$current = &$data;
foreach($keys as $value) {
$parts = explode("/", $value);
$parts_count = count($parts);
foreach($parts as $i => $part) {
if(!array_key_exists($part, $current)) {
if($i == $parts_count - 1) {
$current[] = $part;
}
else {
$current[$part] = array();
$current = &$current[$part];
}
}
else {
$current = &$current[$part];
}
}
$current = &$data;
}
$keys beeing the flat array.
Although it's not clear from your question how the "/" separated strings will map to an array, the basic approach will probably be something like this:
$result = array();
$k1 = $k2 = '';
ksort($yourData); // This is the key (!)
foreach ($yourData as $k => $v) {
// Use if / else if / else if to watch for new sub arrays and change
// $k1, $k2 accordingly
$result[$k1][$k2] = $v;
}
This approach uses the ksort to ensure that keys at the same "level" appear together, like this:
'invoice/products/data1/item1'
'invoice/products/data1/item2'
'invoice/products/data2/item3'
'invoice/products2/data3/item4'
'invoice/products2/data3/item5'
Notice how the ksort corresponds to the key grouping you're aiming for.

Dynamically creating/inserting into an associative array in PHP

I'm trying to build an associative array in PHP dynamically, and not quite getting my strategy right. Basically, I want to insert a value at a certain depth in the array structure, for instance:
$array['first']['second']['third'] = $val;
Now, the thing is, I'm not sure if that depth is available, and if it isn't, I want to create the keys (and arrays) for each level, and finally insert the value at the correct level.
Since I'm doing this quite a lot in my code, I grew tired of doing a whole bunch of "array_key_exists", so I wanted to do a function that builds the array for me, given a list of the level keys. Any help on a good strategy for this is appreciated. I'm sure there is a pretty simple way, I'm just not getting it...
php doesn't blame you if you do it just so
$array['first']['second']['third'] = $val;
print_r($array);
if you don't want your keys to be hard coded, here's a flexible solution
/// locate or create element by $path and set its value to $value
/// $path is either an array of keys, or a delimited string
function array_set(&$a, $path, $value) {
if(!is_array($path))
$path = explode($path[0], substr($path, 1));
$key = array_pop($path);
foreach($path as $k) {
if(!isset($a[$k]))
$a[$k] = array();
$a = &$a[$k];
}
$a[$key ? $key : count($a)] = $value;
}
// example:
$x = array();
array_set($x, "/foo/bar/baz", 123);
array_set($x, "/foo/bar/quux", 456);
array_set($x, array('foo', 'bah'), 789);
Create a function like:
function insert_into(&$array, array $keys, $value) {
$last = array_pop($keys);
foreach($keys as $key) {
if(!array_key_exists($key, $array) ||
array_key_exists($key, $array) && !is_array($array[$key])) {
$array[$key] = array();
}
$array = &$array[$key];
}
$array[$last] = $value;
}
Usage:
$a = array();
insert_into($a, array('a', 'b', 'c'), 1);
print_r($a);
Ouput:
Array
(
[a] => Array
(
[b] => Array
(
[c] => 1
)
)
)
That's tricky, you'd need to work with references (or with recursion, but I
chose references here):
# Provide as many arguments as you like:
# createNestedArray($array, 'key1', 'key2', etc.)
function createNestedArray(&$array) {
$arrayCopy = &$array;
$args = func_get_args();
array_shift($args);
while (($key = array_shift($args)) !== false) {
$arrayCopy[$key] = array();
$arrayCopy = &$arrayCopy[$key];
}
}
<?php
function setElements(&$a, array $path = [], $values = [])
{
if (!is_array($path)) {
$path = explode($path[0], substr($path, 1));
}
$path = "[ '" . join("' ][ '", $path) . "' ]";
$code =<<<CODE
if(!isset(\$a{$path})){
\$a{$path} = [];
}
return \$a{$path}[] = \$values;
CODE;
return eval($code);
}
$a = [];
setElements($a, [1,2], 'xxx');
setElements($a, [1,2,3], 233);
setElements($a, [1,2,4], 'AAA');
setElements($a, [1,2,3,4], 555);
print_r($a);
Output
Array
(
[1] => Array
(
[2] => Array
(
[0] => xxx
[3] => Array
(
[0] => 233
[4] => Array
(
[0] => 555
)
)
[4] => Array
(
[0] => AAA
)
)
)
)
You should check it here http://sandbox.onlinephpfunctions.com/

Categories