Multidimensional Array to String conversion - php

I have a dynamic multidimensional array and I want to convert it to string.
here is an example:
Array
(
[data] => check
[test1] => Array
(
[data] => Hello
)
[test2] => Array
(
[data] => world
)
[test3] => Array
(
[data] => bar
[tst] => Array
(
[data] => Lorem
[bar] => Array
(
[data] => doller
[foo] => Array
(
[data] => sit
)
)
)
)
[test4] => Array
(
[data] => HELLO
[tst] => Array
(
[data] => ipsum
[bar] => Array
(
[data] => Lorem
)
)
)
)
The example for string is:
check&hello&world&bar...lorem&doller...sit ....
I have tried alot of things. I even checked the solutions given on other SO questions. like:
Convert Multidimensional array to single array & Multidimensional Array to String
But No luck.

You can simply use array_walk_recursive like as
$result = [];
array_walk_recursive($arr, function($v) use (&$result) {
$result[] = $v;
});
echo implode('&', $result);
Demo

First convert it to flat array, by
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($input_array));
$flat = iterator_to_array($it, false);
false prevents array key collision.
Then use implode,
$str = implode('&', $flat);

You can use following recursive function to convert any multidimensional array to string
public function _convertToString($data,&$converted){
foreach($data as $key => $value){
if(is_array($value)){
$this->_convertToString($value,$converted);
}else{
$converted .= '&'. $value;
}
}
}
You can call above function in following way:
$str = array(
"data" => "check",
"test1" => array(
"data" => "Hello",
"test3" => array(
"data" => "satish"
)
),
"test2" => array(
"data" => "world"
)
);
$converted = "";
//call your function and pass your array and reference string
$this->_convertToString($str,$converted);
echo $converted;
Output will be following:
check&Hello&satish&world
you can modify code to meet your requirement.
Let me know if any further help required.

php has some build in functions that can do this. Like var_dump, json_encode and var_export. But if you want to control the output more it can be doen with a recursive function
function arrToStr(array $data)
{
$str = "";
foreach ($data as $val) {
if (is_array($val)) {
$str .= arrToStr($val);
} else {
$str .= $val;
}
}
return $str;
}
You can format extra line breaks and spaces at will with this.

I would use recursion for this type of array :
echo visit($your_array);
function visit($val){
if( !is_array($val) ){
return $val;
}
$out="";
foreach($val as $v){
$out.= "&".visit($v);
}
return $out;
}

Related

How to transfer one array to another array in php

I have a simple Two array
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
When I print this arrays it should be like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
)
)
Array
(
[0] => Array
(
[demo] => 22
)
)
But I want to create third array which will be show demo kye value into first array like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
[demo] => 22
)
)
Can we do two array into single array in PHP like Above
Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$result[] = array_merge($ages[0],$ages1[0]);
This would do the job.
<?php
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);
// Function to prepend arrays
function prepend_array()
{
$num_args = count(func_get_args());
$new_array = array();
foreach (func_get_args() as $params){
foreach($params as $out_key => $param)
{
foreach($param as $key => $value)
$new_array[$out_key][$key] = $value;
}
}
return $new_array;
}

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

array conversion with in array PHP

i need to convert bellow array from
Array
(
[Property] => Array
(
[S] => Built As Condominium
)
)
to
Array
(
[property] => Built As Condominium
)
is their any way.
You could use an implode under a foreach
<?php
$arr=Array ( 'Property' => Array ( 'S' => 'Built As Condominium' ) );
foreach($arr as $k=>$arr1)
{
$arr[$k]=implode('',$arr1);
}
print_r($arr);
Demo
you can use the key of the array to implode the value in one line for example
$array['Property'] = $array['Property']['S'];
Results
Array ( [property] => Built As Condominium )
$data = array(
"Property" => array(
"S" => "Built As Condominium"
)
);
foreach($data as $key => $value) {
if($key == "Property") {
$normalized_data['Property'] = is_array($value) && isset($value['S']) ? $value['S'] : NULL;
}
}
Program Output
array(1) {
["property"]=>
string(20) "Built As Condominium"
}
Link
Implode is not necessary, or keys, just use a reference, i.e. the '&'. This is nice and simple.
$array = Array ( 'Property' => Array ( 'S' => 'Built As Condominium' ) );
foreach($array as &$value){
$value=$value['S'];
}
or.... if you don't know the key of the inner array but only care about its value (and assuming you want the first member of the inner array as your new value) then something like reset inside a foreach loop would work:
$arr = array ('Property' => array( 'S' => 'Built As Condominium'));
$new = array();
foreach($arr as $key => $inner) {
$new[$key] = reset($inner);
}
print_r($new);
output:
Array
(
[Property] => Built As Condominium
)

json encode return as objects instead array

I have already read this question and doesn't answer my issue.
I have an Array like this:
Array
(
[0] => Array
(
[COM] => 10659.68
)
[1] => Array
(
[MCD] => 1219.09
)
[2] => Array
(
[MCR] => 77047.65
)
)
And when I make a json_encode() it return this;
[{"COM":10659.68},{"MCD":1219.09},{"MCR":77047.65}]
What I need is get the data in this way:
[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]
Any idea how can I achieve this
Even though that's not a valid JSON, you can replace the { with [
echo str_replace(array('{','}'),array('[',']'),json_encode($your_array));
Depending on the content you might need a more complex replacement with regular expressions.
More complex solution:
function toJson($arr){
$return = array();
foreach($arr as $k => $v){
if(is_array($v)) $return[] = toJson($v);
else $return[] = sprintf('"%s":%s', $k, $v);
}
return sprintf('[%s]', implode(',', $return));
}
Test:
$input = array(
array('COM' => '10659.68'),
array('MCD' => '1219.09'),
array('MCR' => '77047.65'),
);
var_dump(toJson($input));
string(51) "[["COM":10659.68],["MCD":1219.09],["MCR":77047.65]]"

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