convert array into key value pairs - php

I have following array,
Array
(
[Char100_1] => Array
(
[0] => Array
(
[Char100_1] => Mr S Kumar
)
[1] => Array
(
[Char100_1] => Mr S Kumar2
)
)
[Char100_13] => Array
(
[0] => Array
(
[Char100_13] => 159.9
)
[1] => Array
(
[Char100_13] => 119.9
)
)
[Char100_14] => Array
(
[0] => Array
(
[Char100_14] => 191.88
)
[1] => Array
(
[Char100_14] => 143.88
)
)
)
which is created dynamically from a database query result and some loops.
Now I wanted to convert this array into something like below,
Array
(
[0] => Array
(
[Char100_1] => Mr S Kumar
[Char100_13] => 159.9
[Char100_14] => 191.88
)
[1] => Array
(
[Char100_1] => Mr S Kumar2
[Char100_13] => 119.9
[Char100_14] => 143.88
)
)
I have tried looping through them but its not working.
<?php
/* database process to create array */
$contentArray = array();
foreach($newData['DataField'] as $ndata) :
$responsedata = getAppContent($appid, $ndata);
while($haveresult = mysql_fetch_assoc($responsedata))
{
$contentArray[$ndata][] = $haveresult;
}
endforeach;
/* for getting resulting array start */
$newdataArray = array();
foreach($contentArray as $field => $value):
$newdataArray[$field] = array();
foreach( $value as $val ) :
$newdataArray[$field] = $val;
endforeach;
endforeach;
?>

If you can't change the query (as suggested in the comments), then the following should work:
$output = array();
foreach ($array as $a) {
foreach ($a as $k => $b) {
if (empty($output[$k])) {
$output[$k] = array();
}
$output[$k] += $b;
}
}

I observe that you are transposing the arrays. i.e all the zero subscript values together and all the one subscript values together.
Therefore your outer subscript should be the '0' and '1'. These are available in the inner loop. So, the inner loop index becomes the outer array index. And the inner loop value, which is an array, you need to take the 'current' value of.
/* for getting resulting array start (PHP 5.3.18) */
$newdataArray = array();
foreach($contentArray as $field => $value):
foreach( $value as $idx => $val ): // $idx takes value 0 or 1. $val is an array
$newdataArray[$idx][$field] = current($val);
endforeach;
endforeach;
print_r($newdataArray);

As long as all of your arrays have the same amount of values containing them a for loop will do:
$NewDataArray = array();
for ($a = 0; $a < $Numberofvaluesineacharray; $a++){
$NewDataArray[$a] = $NewDataArray[$array1[$a], $array2[$a],.....arrayn[$a];
}

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

unable to set array values in two php foreach loops

I have defined two arrays as
$array1 = (8,10);
Array2 was array of stdobjects which was later converted into below using json decode, encode. Php echo output of the same is below:
$array2 = Array
(
[0] => Array
(
[id] => 6
)
[1] => Array
(
[id] => 8
)
[2] => Array
(
[id] => 10
)
)
Later I created one array
foreach( $array2 as $value )
{
$valuesArray[] = array('',$value['id'],Input::get('date'),'0');
}
What I am trying to do is compare array1 with valuesarray. If $value['id'] i.e. second element matches with any of the element in array1, I will save 4th element of $nnn as 1. If it doesnt match with any of the element, I will save it as 0.
My code below:
foreach ($valuesArray as $value2)
{
foreach ($array1 as $value1)
{
if ($value2[1] == $value1)
{$x = 1;}
else
{$x = 0;}
}
$nnn[] = "('','".$value2[1]."','".Input::get('date')."','".$x."')";
}
echo '<pre>',print_r($nnn,1),'</pre>';
The output that I am getting is:
Array
(
[0] => ('','6','2016-04-25','0')
[1] => ('','8','2016-04-25','0')
[2] => ('','10','2016-04-25','1')
)
Correct output should be:
Array
(
[0] => ('','6','2016-04-25','1')
[1] => ('','8','2016-04-25','1')
[2] => ('','10','2016-04-25','0')
)
try this:
$nnn = array();
foreach ($valuesArray as $value) {
$x = (in_array($value[1], $array1))?1:0;
$nnn[] = "('','".$value[1]."','".Input::get('date')."','{$x}')";
}

Convert Multi dimensional array PHP

I want to convert multi dimensional array in Php
I'm stuck in logic.. Kindly help
Thanks in advance
Current Produced array :
Array
(
[5316] => Array
(
[0] => Array
(
[PROD1] => color=black
)
[1] => Array
(
[PROD1] => paper=a1
)
[2] => Array
(
[PROD2] => color=metallic_silver
)
[3] => Array
(
[PROD2] => paper=a1
)
)
)
I want to convert this array into this form
Array
(
[5316] => Array
(
[PROD1] => Array
(
color => black
paper => a1
)
[PROD2] => Array
(
color => metallic_silver
paper => a1
)
)
)
If you can't hardcode that key to directly point to it, you can use reset() in this case, then grouped them inside a foreach accordingly. Example:
$array = array(
5316 => array(
array('PROD1' => 'color=black'),
array('PROD1' => 'paper=a1'),
array('PROD2' => 'color=metallic_silver'),
array('PROD2' => 'paper=a1'),
),
);
$grouped = array();
// point it to the first key which gives an array of those values
foreach (reset($array) as $key => $value) {
reset($value); // reset the internal pointer of the sub array
$key = key($value); // this return `PROD1, PROD2`
$grouped[$key][] = current($value); // current gives color=black, the values
}
$array[key($array)] = $grouped; // then reassign
echo '<pre>';
print_r($array);
Sample Output
You can try something like below.
$newArr = [];
$count = count($arr[5316]);
for($i = 0, $j = 1; $i < $count; $i += 2){
$color = explode('=', $arr[5316][$i]['PROD'.$j]);
$paper = explode('=', $arr[5316][$i+1]['PROD'.$j]);
$newArr[5316]['PROD'.$j] = array('color'=>$color[1], 'paper'=>$paper[1]);
$j++;
}
//To show output
print '<pre>';
print_r($newArr);
print '</pre>';

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

How to change index of the multidimentional array below?

How to change this bellow array
Array
(
[0] => Array
(
[0] => Array
(
[0] => 35.2
)
[1] => Array
(
[0] => 49.5
)
)
[1] => Array
(
[0] => Array
(
[0] => 44
)
[1] => Array
(
[0] => 38.5
)
)
)
into
Array
(
[0] => Array
(
[0] => 35.2
[1] =>49.5
)
[1] => Array
(
[0] => 44
[1] => 38.5
)
)
The easy, easy way is a simple nested foreach:
// be sure to include the &. Otherwise your edits will do nothing.
foreach( $input as &$level1 )
{
// level 1 is the array of the arrays which contain your values
// we need the keys and the arrays which hold the desired values
foreach( $level1 as $key => $level2 )
{
// assign the key to be the value at 0 instead of its current value
// (which happens to be level2)
$level1[ $key ] = $level2[ 0 ];
}
}
Sheepy proposed use of array_merge with call_user_func_array below. That is a good idea and I gave it a +1. (I encourage others to do the same). To see which was better, I decided to run a benchmark on both solutions:
The results:
manual 0.074267864227295
call_usr_func_array 0.13694596290588
manual 0.080928087234497
call_usr_func_array 0.13510608673096
I then reversed test order:
call_usr_func_array 0.14956903457642
manual 0.066309928894043
call_usr_func_array 0.14821600914001
manual 0.064701080322266
Here's the benchmark code:
$st = microtime(1);
$input = array();
for( $i = 0; $i < 10000; $i++ )
$input[] = array( array( 1 ),array( 2 ),array( 3 ) );
// be sure to include the &. Otherwise your edits will do nothing.
foreach( $input as &$level1 )
{
// level 1 is the array of the arrays which contain your values
// we need the keys and the arrays which hold the desired values
foreach( $level1 as $key => $level2 )
{
// assign the key to be the value at 0 instead of its current value
// (which happens to be level2)
$level1[ $key ] = $level2[ 0 ];
}
}
print microtime(1) - $st;
print PHP_EOL;
$st = microtime(1);
$input = array();
for( $i = 0; $i < 10000; $i++ )
$input[] = array( array( 1 ),array( 2 ),array( 3 ) );
foreach ( $input as $k => $ary ) {
$input[$k] = call_user_func_array ( 'array_merge' , $ary );
}
print microtime(1) - $st;
Here is a shorter version. It is still a nested loop in reality, though.
foreach ( $input as $k => $ary ) {
$input[$k] = call_user_func_array ( array_merge , $ary );
}

Categories