array conversion with in array PHP - 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
)

Related

array_combine() expects parameter 2 to be array, string given in php

Array
(
[0] => tttt
[1] => tttt
)
$terms_keys = array("terms");
$terms_array = array();
foreach ( array_map(null,$inv_terms) as $key => $value ) {
$terms_array[] = array_combine($terms_keys, $value);
}
what is mistake done in my code ?
The $value param in the foreach is of course not an array its a scalar tttt, so you could make it into an array by doing [$value] in the combine
$terms_keys = array("terms");
$terms_array = array();
foreach ( array_map(null,$inv_terms) as $key => $value ) {
$terms_array[] = array_combine($terms_keys, [$value]);
}
Or simplified as the array_map() does not achieve anything
$terms_keys = array("terms");
$terms_array = array();
foreach ( $inv_terms as $key => $value ) {
$terms_array[] = array_combine($terms_keys, [$value]);
}
I don't understand how it could be advantageous to bloat your array structure with more depth, but generating the indexed array of associative arrays can be done without iterated function calls. Just push the values into their new deep location using square-brace pushing syntax in a body-less foreach loop.
Code: (Demo)
$inv_terms = ['tttt', 'tttt'];
$result = [];
foreach ($inv_terms as $result[]['terms']);
var_export($result);
Output:
array (
0 =>
array (
'terms' => 'tttt',
),
1 =>
array (
'terms' => 'tttt',
),
)

Multidimensional Array to String conversion

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;
}

Working with arrays to produce a single array

I have an array that can have many values at any given point, what I would like to accomplish is to combine all the array indexes and form one index with my final value. Merge other values that are the same
Say I have the array result below
Array
(
[0] => stdClass Object
(
[component] => sodium chloride
[generic_results] => Average:=99.20%
)
[1] => stdClass Object
(
[component] => sodium chloride
[generic_results] => RSD:=0.54%
)
[2] => stdClass Object
(
[component] => sodium chloride
[generic_results] => n:=3
)
)
What I would like is something like this
Array
(
[0] => stdClass Object
(
[component] => sodium chloride
[generic_results] => Average:=99.20%,RSD:=0.54%, n:=3
)
)
I have tried array unique but its not working.
Example code generating the results:
$arr=array(
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'Average:=99'
),
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'RSD:=0.54'
),
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'n:=3'
)
);
print('<pre>');
print_r($arr);
print('</pre>');
Any Suggestions for this problem?
Try this
$new = array();
foreach ($array as $obj){
// By setting the key you guarantee it being unique
$new[$obj->component][$obj->generic_results] = $obj->generic_results;
}
$new2 = array();
foreach ($new as $comp=>$arr){
$new2['component'][$comp] = implode(',',$arr);
}
This will return an array but you can (although its not always sufficient) then use json_decode(json_encode($new2), false) to convert it to the object. Hope that helps.
You can use array_reduce, which iterates over an array to combine all elements with a given callback function:
$result = array_reduce($arr, function($result, $item) {
if ($result === null) {
// initialize with first item
return [$item];
}
// add generic_results of current item to result
$result[0]->generic_results .= ',' . $item->generic_results;
return $result;
}
);
Demo: https://3v4l.org/KBUBl

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

Replace key of array with the value of another array while looping through

I have two multidimensional arrays. First one $properties contains english names and their values. My second array contains the translations. An example
$properties[] = array(array("Floor"=>"5qm"));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden"));
$translations[] = array(array("Height"=>"Höhe"));
(They are multidimensional because the contains more elements, but they shouldn't matter now)
Now I want to translate this Array, so that I its at the end like this:
$properties[] = array(array("Boden"=>"5qm"));
$properties[] = array(array("Höhe"=>"10m"));
I have managed to build the foreach construct to loop through these arrays, but at the end it is not translated, the problem is, how I tell the array to replace the key with the value.
What I have done is this:
//Translate Array
foreach ($properties as $PropertyArray) {
//need second foreach because multidimensional array
foreach ($PropertyArray as $P_KiviPropertyNameKey => $P_PropertyValue) {
foreach ($translations as $TranslationArray) {
//same as above
foreach ($TranslationArray as $T_KiviTranslationPropertyKey => $T_KiviTranslationValue) {
if ($P_KiviPropertyNameKey == $T_KiviTranslationPropertyKey) {
//Name found, save new array key
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
}
}
}
}
}
The problem is with the line where to save the new key:
$P_KiviPropertyNameKey = $T_KiviTranslationValue;
I know this part is executed correctly and contains the correct variables, but I believe this is the false way to assing the new key.
This is the way it should be done:
$properties[$oldkey] = $translations[$newkey];
So I tried this one:
$PropertyArray[$P_KiviPropertyNameKey] = $TranslationArray[$T_KiviTranslationPropertyKey];
As far as I understood, the above line should change the P_KiviPropertyNameKey of the PropertyArray into the value of Translation Array but I do not receive any error nor is the name translated. How should this be done correctly?
Thank you for any help!
Additional info
This is a live example of the properties array
Array
(
[0] => Array
(
[country_id] => 4402
)
[1] => Array
(
[iv_person_phone] => 03-11
)
[2] => Array
(
[companyperson_lastname] => Kallio
)
[3] => Array
(
[rc_lot_area_m2] => 2412.7
)
[56] => Array
(
[floors] => 3
)
[57] => Array
(
[total_area_m2] => 97.0
)
[58] => Array
(
[igglo_silentsale_realty_flag] => false
)
[59] => Array
(
[possession_partition_flag] => false
)
[60] => Array
(
[charges_parkingspace] => 10
)
[61] => Array
(
[0] => Array
(
[image_realtyimagetype_id] => yleiskuva
)
[1] => Array
(
[image_itemimagetype_name] => kivirealty-original
)
[2] => Array
(
[image_desc] => makuuhuone
)
)
)
And this is a live example of the translations array
Array
(
[0] => Array
(
[addr_region_area_id] => Maakunta
[group] => Kohde
)
[1] => Array
(
[addr_town_area] => Kunta
[group] => Kohde
)
[2] => Array
(
[arable_no_flag] => Ei peltoa
[group] => Kohde
)
[3] => Array
(
[arableland] => Pellon kuvaus
[group] => Kohde
)
)
I can build the translations array in another way. I did this like this, because in the second step I have to check, which group the keys belong to...
Try this :
$properties = array();
$translations = array();
$properties[] = array("Floor"=>"5qm");
$properties[] = array("Height"=>"10m");
$translations[] = array("Floor"=>"Boden");
$translations[] = array("Height"=>"Höhe");
$temp = call_user_func_array('array_merge_recursive', $translations);
$result = array();
foreach($properties as $key=>$val){
foreach($val as $k=>$v){
$result[$key][$temp[$k]] = $v;
}
}
echo "<pre>";
print_r($result);
output:
Array
(
[0] => Array
(
[Boden] => 5qm
)
[1] => Array
(
[Höhe] => 10m
)
)
Please note : I changed the array to $properties[] = array("Floor"=>"5qm");, Removed a level of array, I guess this is how you need to structure your array.
According to the structure of $properties and $translations, you somehow know how these are connected. It's a bit vague how the indices of the array match eachother, meaning the values in $properties at index 0 is the equivalent for the translation in $translations at index 0.
I'm just wondering why the $translations array need to have the same structure (in nesting) as the $properties array. To my opinion the word Height can only mean Höhe in German. Representing it as an array would suggest there are multiple translations possible.
So if you could narrow down the $translations array to an one dimensional array as in:
$translation = array(
"Height"=>"Höhe",
"Floor"=>"Boden"
);
A possible loop would be
$result = array();
foreach($properties as $i => $array2) {
foreach($array2 as $i2 => $array3) {
foreach($array3 as $key => $value) {
$translatedKey = array_key_exists($key, $translations) ?
$translations[$key]:
$key;
$result[$i][$i2][$translatedKey] = $value;
}
}
}
(I see every body posting 2 loops, it's an array,array,array structure, not array,array ..)
If you cannot narrow down the translation array to a one dimensional array, then I'm just wondering if each index in the $properties array matches the same index in the $translations array, if so it's the same trick by adding the indices (location):
$translatedKey = $translations[$i][$i2][$key];
I've used array_key_exists because I'm not sure a translation key is always present. You have to create the logic for each case scenario yourself on what to check or not.
This is a fully recursive way to do it.
/* input */
$properties[] = array(array("Floor"=>"5qm", array("Test"=>"123")));
$properties[] = array(array("Height"=>"10m"));
$translations[] = array(array("Floor"=>"Boden", array("Test"=>"Foo")));
$translations[] = array(array("Height"=>"Höhe"));
function array_flip_recursive($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_flip_recursive($val);
}
else {
$arr = #array_flip($arr);
}
}
return $arr;
}
function array_merge_it($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_merge_it($val);
} else {
if(isset($arr[$key]) && !empty($arr[$key])) {
#$arr[$key] = $arr[$val];
}
}
}
return $arr;
}
function array_delete_empty($arr) {
foreach ($arr as $key => $val) {
if (is_array($val)) {
$arr[$key] = array_delete_empty($val);
}
else {
if(empty($arr[$key])) {
unset($arr[$key]);
}
}
}
return $arr;
}
$arr = array_replace_recursive($properties, $translations);
$arr = array_flip_recursive($arr);
$arr = array_replace_recursive($arr, $properties);
$arr = array_merge_it($arr);
$arr = array_delete_empty($arr);
print_r($arr);
http://sandbox.onlinephpfunctions.com/code/d2f92605b609b9739964ece9a4d8f389be4a7b81
You have to do the for loop in this way. If i understood you right (i.e) in associative array first key is same (some index).
foreach($properties as $key => $values) {
foreach($values as $key1 => $value1) {
$propertyResult[] = array($translations[$key][$key1][$value1] => $properties[$key][$key1][$value1]);
}
}
print_r($propertyResult);

Categories