How to change index of the multidimentional array below? - php

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

Related

Build SQL query from multiple arrays - PHP

I've got an array that looks like this..
Array
(
[fm] => Array
(
[133.74] => Array
(
[base] => Array
(
[0] => 2015-09-29
[1] => 2015-09-30
)
)
[202.59] => Array
(
[base] => Array
(
[0] => 2015-10-01
)
)
)
[fmtax] => Array
(
[13.51] => Array
(
[0] => 2015-09-29
[1] => 2015-09-30
)
[20.46] => Array
(
[0] => 2015-10-01
)
)
)
and I need to build a SQL statement to insert the relevant values. I'm thinking it will need to be a unique query for each array item.
So I'll end up needing something like
$sql = "insert into mytable ('price', 'tax', 'date')
values ('133.74', '13.51', '2015-09-29')";
What I've got so far is this...
foreach ($sale['fm'] as $key => $value) {
$i=0;
$g=count($value['base']);
while($i < $g) {
echo($sale['fm'][$key]['base'][$i]."<br />");
$i++;
}
}
which does well for the "fm" key - but I'm getting hung up on how to grab the value from the second associated "fmtax" array key. I was thinking using something like current/next as it iterates through...but am kinda scratching my head on it.
I am assuming that fm and fmtax both have same number of elements and the order of related elements (price and tax) from fm and fmtax are same. What you can do is - store the taxes from fmtax with simple keys in this way :
$taxes = array();
$c = 0;
foreach ($sale['fmtax'] as $key => $value) {
$taxes[$c] = $key;
$c++;
}
Then you can access this new $taxes array from your own code block in this way :
$c = 0;
foreach ($sale['fm'] as $key => $value) {
//Here you have the related tax
$tax = $taxes[$c];
$i=0;
$g=count($value['base']);
while($i < $g) {
echo($sale['fm'][$key]['base'][$i]."<br />");
$i++;
}
$c++;
}

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

Associative index array to associative associative array

Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...

convert array into key value pairs

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

if we have 5 different array how to merge them in single array in php

I have 5 different array whose structure is :-
Array ( [0] => http://www.php.net/200
)
Array ( [0] => http://www.php.net/?setbeta=1&beta=1302
)
Array ( [0] => http://www.php.net/downloads.php200
)
Array ( [0] => http://www.php.net/docs.php200
)
Array ( [0] => http://www.php.net/FAQ.php302
)
I need to merge these all in a single array whose structure would be like:-
Array ( [0] => http://www.php.net/200
[1] => http://www.php.net/?setbeta=1&beta=1302
[2] => http://www.php.net/downloads.php200
[3] => http://www.php.net/docs.php200
[4] => http://www.php.net/FAQ.php302
)
One thing i want to confirm that these arrays are forming inside a loop function and it could be of any number and also they have a single name i.e $array
Simplest is probably just array_merge().
$merged = array_merge( $ar1, $ar2, $ar3, $ar4, $ar5 );
Use array_merge.
$arr = array_merge($arr1,$arr2,$arr3,$arr4,$arr5);
Edit After seeing your comment, you are having multidimensional array.
$arr = array();
for($i = 0; $i < $old_arr; $i++) {
$arr[] = $old_arr[$i][0];
}
Use array_merge
$arr1=Array ( 0 => 'http://www.php.net/200');
$arr2=Array( 0 => 'http://www.php.net/?setbeta=1&beta=1302');
$arr3=Array( 0 => 'http://www.php.net/downloads.php200');
$merged=array_merge($arr1,$arr2,$arr3);
print_r($merged);
$newarray = array();
while ( is_array( array_get_function_here() ) )
{
$newarray = array_merge( $newarray, $array );
}
I would try that if you get the different arrays in a looping function.
The above $array is something that array_get_function_here() should return for the while loop validity check (if it returns and array, the while check runs as true). array_get_function_here() is just an example and should be some function that returns a value for $array.

Categories