multidimensional array implode whole inner array elements function in php - php

Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
)
[2] => Array
(
[0] => d
[1] => e
[2] => f
)
)
I want to convert above two dimensional array into following array using implode or any other function in php
Array
(
[0]=>a,b
[1]=>c
[2]=>d,e,f
)

You can use a loop and implode them and store them -
foreach($yourArray as $key => $array) {
$yourArray[$key] = implode(',', $array);
}
Or array_map also help -
$new = array_map(function($array) {
return implode(',', $array);
}, $yourArray);

$newArray = array();
foreach ($array $k => $v) {
$newArray[$k] = implode(",", $v);
}

If you want to change your existing array,
array_walk($your_array, function(&$v){
$v = implode(',', $v);
});
If you want a new array,
$new_array = array_map('implode', $your_array,
array_fill(0, count($your_array), ',')
);

Related

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"
)
)

Explode array's data and make new array

I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

Create a multicolumn array in PHP from string

I want to create a multicolumn array from a string where the spearator for the first level array is ";" and for the second level array is ","
This string is given:
$string = ("de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3")
This is the structure of the array that i want as result:
Array
(
array([de] => text1, text2, text3),
array([en] => text1, text2, text3),
array([pl] => text1, text2, text3),
)
The solution using array_map, substr, strpos and explode functions:
$string = ("de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3");
$items = array_map(function($v){
$sep_pos = strpos($v, ","); // position of key/values separator
return [substr($v, 0, $sep_pos) => substr($v, $sep_pos + 1)];
}, explode(";", $string));
print_r($items);
The output:
Array
(
[0] => Array
(
[de] => text1,text2,text3
)
[1] => Array
(
[en] => text1,text2,text3
)
[2] => Array
(
[pl] => text1,text2,text3
)
)
You can use array_map and pass array by using explode, and inside callback you can explode again with , and store it in a variable.
there after you can grab the value using array_shift, which needed to be used as a key, and return a new array.
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$result = array_map(function($value) {
$temp = explode(',', $value);
return [array_shift($temp) => implode(',', $temp)];
}, explode(';', $string));
print_r($result);
Example: https://eval.in/581893
Try:
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$mainArr = explode(";",$string);
$finalArr = array();
foreach($mainArr as $arr) {
$tempArr = explode(",",$arr);
reset($tempArr);
$mainK = $tempArr[0];
unset($tempArr[key($tempArr)]);
$finalArr[][$mainK] = implode(",", $tempArr);
}
print '<pre>';print_r($finalArr);print '</pre>';
Output:
Array
(
[0] => Array
(
[de] => text1,text2,text3
)
[1] => Array
(
[en] => text1,text2,text3
)
[2] => Array
(
[pl] => text1,text2,text3
)
)
Try This Code
$string = "de,text1,text2,text3;en,text1,text2,text3;pl,text1,text2,text3";
$array1 = explode(';', $string);
foreach($array1 as $value){
$temp=explode(',', $value);
$key=$temp[0];
unset($temp[0]);
$new_array[][$key]=$temp;
}

How to replace array keys with another array values

I have two arrays and I want to replace the second array keys with the first array values if both keys matches.
As an example: Replace A with Code And B with name
How to do this;
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as $key => $value){
foreach($value as $sk => $sv){
foreach($array as $rk => $rv){
if($sk == $rk ){
$sk = $rv;
}
}
}
}
echo "<pre>";
print_r($value);
echo "</pre>";
exit;
I want the result to be like this
array(
[0] => Array
(
[name] => ahmed
[code] => 1020
)
[1] => Array
(
[name] => sara
[code] => 2020
)
)
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as &$value)
{
foreach ($array as $key => $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
var_dump($replacement_keys);
Try this:
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
$newArray = array();
foreach($replacement_keys as $key => $value)
{
foreach($value as $key2 => $value2)
{
if(isset($array[$key2]))
{
$newArray[$key][$array[$key2]] = $value2;
}
else
{
$newArray[$key][$key2] = $value2;
}
}
}
print_R($newArray);
This should work for you, nice and simple (I'm going to assume that A should be name and B should be code):
(Here I go through each array from $replacement_keys with array_map() and replace the array_keys() with the array_values() of $array. Then I simply get all array values from $replacement_keys and finally I array_combine() the replaced array keys with the corresponding array values)
$result = array_map("array_combine",
array_map(function($v)use($array){
return str_replace(array_keys($array), array_values($array), array_keys($v));
}, $replacement_keys),
$replacement_keys
);
output:
Array ( [0] => Array ( [code] => sara [name] => 2020 ) [1] => Array ( [code] => ahmed [name] => 1010 ) )
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7)
array_fill_keys — Fill an array with values, specifying keys
Description
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
http://php.net/manual/en/function.array-fill-keys.php

Explode multiple comma-separated strings in a 2d array, then get all unique values

I have an 2d array which returns me this values:
Array (
[0] => Array (
[0] => wallet,pen
[1] => perfume,pen
)
[1] => Array (
[0] => perfume, charger
[1] => pen,book
).
Out of this i would like to know if it is possible to create a function which would combine the array going this way,and create a new one :
if for example [0] => Array ( [0] => wallet,pen [1] => perfume,pen ) then should be equal to
[0] => Array ( [0] => wallet,pen, perfume ) because there is a common word else do nothing.
And also after that retrieve each words as strings for further operations.
How can i make the values of such an array unique. Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) ) as there is pen twice i would like it to be deleted in this way ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )
It's just a matter of mapping the array and combining the inner arrays:
$x = [['wallet,pen', 'perfume,pen'], ['perfume,charger', 'pen,book']];
$r = array_map(function($item) {
return array_unique(call_user_func_array('array_merge', array_map(function($subitem) {
return explode(',', $subitem);
}, $item)));
}, $x);
Demo
This first splits all the strings based on comma. They are then merged together with array_merge() and the duplicates are removed using array_unique().
See also: call_user_func_array(), array_map()
Try this :
$array = Array (Array ( "wallet,pen", "perfume,pen" ), Array ( "perfume, charger", "pen,book" ));
$res = array();
foreach($array as $key=>$val){
$temp = array();
foreach($val as $k=>$v){
foreach(explode(",",$v) as $vl){
$temp[] = $vl;
}
}
if(count(array_unique($temp)) < count($temp)){
$res[$key] = implode(",",array_unique($temp));
}
else{
$res[$key] = $val;
}
}
echo "<pre>";
print_r($res);
output :
Array
(
[0] => wallet,pen,perfume
[1] => Array
(
[0] => perfume, charger
[1] => pen,book
)
)
You can eliminate duplicate values while pushing them into your result array by assigning the tag as the key to the element -- PHP will not allow duplicate keys on the same level of an array, so any re-encountered tags will simply be overwritten.
You can use recursion or statically written loops for this task.
Code: (Demo)
$result = [];
foreach ($array as $row) {
foreach ($row as $tags) {
foreach (explode(',', $tags) as $tag) {
$result[$tag] = $tag;
}
}
}
var_export(array_values($result));
Code: (Demo)
$result = [];
array_walk_recursive(
$array,
function($v) use(&$result) {
foreach (explode(',', $v) as $tag) {
$result[$tag] = $tag;
}
}
);
var_export(array_values($result));

Categories