This might be very silly but we have not been able to do this .
We are trying to insert an array into a php file . However we are able to insert the array into a php file but the format is not as desired . We have 2 files .
File1.php
<?php
include_once("../dc/dcCommonLib.php");
include_once("../dc/persistence/UserData.php");
require_once("../../lib/include/connect.inc.php");
$_SESSION["survey"] = "BestBuyAug2012";
$idLink = dbconnect($_SESSION["survey"]);
$surveyWidget = rendererSurveyLoadHandler();
setDataToSession("surveywidget",$surveyWidget);
$userData = &UserData::getInstance();
$userData->setSurvey($surveyWidget);
saveFkidsToOidToFkidMappingArray($userData->OidToFkidMapping);
// prepare demo array
prepareItemArray($userData->OidToFkidMapping["Demographic"]["Q"],$demo,"b");
// prepare item array
prepareItemArray($userData->OidToFkidMapping["Default"]["Q"],$item,"i");
prepareItemArray($userData->OidToFkidMapping["Default"]["M"],$item,"i");
// prepare comment array
prepareCommentArray($userData->OidToFkidMapping["Comment"]["C"],$comment);
if(!function_exists('file_put_contents')) {
function file_put_contents($filename, $data,$type, $file_append = false) {
$fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
if(!$fp) {
trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
return;
}
if($type){
$count = count($data);
$i = 1;
//loop through your type array and append comma , to each except last
foreach($data as $key=>$val) {
//if we are before last key, append comma
if($i < $count)
$data[$key] .= ',';
$i++;
}
//run same preg_replace as before
$data2 = preg_replace('/[\[\]]/','"',print_r($data,TRUE));
//write to file
fputs($fp, "$" . $type . " = " . print_r($data2,TRUE));
} else {
fputs($fp, print_r($data, TRUE));
}
fclose($fp);
}
}
print("Strart writting ...................");
file_put_contents("staticSurveyDataFileTest.php", "<?php\n","",true);
file_put_contents("staticSurveyDataFileTest.php", $item,"itemFkids",true);
file_put_contents("staticSurveyDataFileTest.php", $demo,"demoFkids",true);
file_put_contents("staticSurveyDataFileTest.php", $comment,"commentFkids",true);
file_put_contents("staticSurveyDataFileTest.php", "?>","",true);
print("written ...");
function prepareItemArray($userDataArray, &$item, $itemStr) {
if(is_array($userDataArray)) {
foreach($userDataArray as $questId=>$respGrp) {
$selectionGrp=array_unique($respGrp);
if(count($selectionGrp)==1) {
$respGrpId=key($respGrp);
$respId = key($respGrp[$respGrpId]);
$item[$questId."_".key($respGrp)]=$itemStr.$respGrp[$respGrpId][$respId];
}else {
foreach ($respGrp as $respGrpId=>$resp) {
$respGrp[$respGrpId]=$itemStr.$resp;
}
$item[$questId."_".key($respGrp)]=$respGrp;
}
}
}
}
function prepareCommentArray($userDataArray, &$item) {
if(is_array($userDataArray)) {
foreach($userDataArray as $questId=>$respGrp) {
$selectionGrp=array_unique($respGrp);
if(count($selectionGrp)==1) {
$respGrpId=key($respGrp);
$item[$questId."_".key($respGrp)]=$respGrp[$respGrpId]["fk_id"];
}
}
}
}
?>
The array from this file is inserted into staticSurveyDataFileTest.php
staticSurveyDataFileTest.php
<?php
$itemFkids = Array
(
"203_19" => i27,//double quotes missing for all the lines . See below for desired output//
"207_22" => i28,
"357_22" => i99,
"370_70" => i104,
"377_72" => i105,
"140_8" => i1,
"141_8" => i2,
"142_8" => i3,
"143_8" => i4,
"144_8" => i5,
"145_8" => i6,
"151_8" => i7,
"152_8" => i8,
"158_8" => i9,
"164_8" => i10,
"165_8" => i11,
"166_8" => i12,
"167_8" => i13,
"168_8" => i14,
"169_8" => i15,
"175_8" => i16,
"176_8" => i17,
"182_8" => i18,
"183_8" => i19,
"184_8" => i20,
"190_8" => i21,
"196_8" => i22,
"197_8" => i23,
"198_8" => i24,
"199_8" => i25,
"200_8" => i26,
"214_8" => i29,
"215_8" => i30,
"216_8" => i31,
"222_8" => i32,
"223_8" => i33,
"224_8" => i34,
"225_8" => i35,
"226_8" => i36,
"227_8" => i37,
"233_8" => i38,
"234_8" => i39,
"235_8" => i40,
"236_8" => i41,
"237_8" => i42,
"243_8" => i43,
"244_8" => i44,
"245_8" => i45,
"251_8" => i46,
"252_8" => i47,
"253_8" => i48,
"254_8" => i49,
"255_8" => i50,
"256_8" => i51,
"257_8" => i52,
"263_8" => i53,
"264_8" => i54,
"265_8" => i55,
"266_8" => i56,
"267_8" => i57,
"268_8" => i58,
"269_8" => i59,
"270_8" => i60,
"271_8" => i61,
"272_8" => i62,
"278_8" => i63,
"279_8" => i64,
"280_8" => i65,
"281_8" => i66,
"282_8" => i67,
"283_8" => i68,
"289_8" => i69,
"290_8" => i70,
"296_8" => i71,
"297_8" => i72,
"298_8" => i73,
"299_8" => i74,
"300_8" => i75,
"301_8" => i76,
"307_8" => i77,
"308_8" => i78,
"309_8" => i79,
"310_8" => i80,
"311_8" => i81,
"312_8" => i82,
"313_8" => i83,
"314_8" => i84,
"315_8" => i85,
"316_8" => i86,
"317_8" => i87,
"318_8" => i88,
"324_26" => i89,
"328_37" => i90,
"332_48" => i91,
"338_59" => i92,
"344_59" => i93,
"345_59" => i94,
"351_8" => i95,
"352_8" => i96,
"353_8" => i97,
"354_8" => i98,
"364_8" => i100,
"365_8" => i101,
"366_8" => i102,
"367_8" => i103
)//comma missing
$demoFkids = Array
(
"129_2" => b1
)//comma missing
$commentFkids = Array
(
"373_375" => 1,
"380_382" => 2
)//comma missing
?>
We need to insert a file something like this
Desired Output
<?php
$itemFkids = Array
(
"203_19" => "i27",//notices the double quotes here
"207_22" => "i28",
"357_22" => "i99",
.
.
.
.
.
.
),//notice a comma here
$demoFkids = Array
(
"129_2" => "b1"//notices the double quotes here
),//notice a comma here
$commentFkids = Array
(
"373_375" => "1",
"380_382" => "2"//notices the double quotes here
),//notice a comma here
?>
Thanks for your help in advance :)
You can use something like this:
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>
And this outputs:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
)
Check out the documentation at http://php.net/manual/fr/function.var-export.php
Code for the desired output:
<?php
$result = array_merge($itemFkids, $demoFkids, $commentFkids);
var_export($result);
?>
Outputs:
<?php
$itemFkids = Array
(
"203_19" => "i27",
"207_22" => "i28",
"357_22" => "i99",
.
.
.
),
$demoFkids = Array
(
"129_2" => "b1"
),
$commentFkids = Array
(
"373_375" => "1",
"380_382" => "2"
),
?>
Cannot reliably say until we work with the full code! :)
try using the php function var_export
Even trying this is worth:
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
The output of the above is:
object(A)#2 (2) {
["var1"]=>
int(5)
["var2"]=>
string(3) "foo"
}
Related
What I'm trying to accomplish is to write a html string in a controller with array values being looped in it. So for example;
$content = "Your store, at location A, has these items added to them". add array loop here. "Do take note!";
My array would be as such
array (
0 =>
array (
'id' => '5db29b6d31c391731239bbdf',
'name' => 'Diamond bracelet (sample)',
'tags' =>
array (
0 => 'female',
1 => 'jewelry',
),
'category' => 'Accessories',
'sku' => '1029EHW',
'priceType' => 'Fixed',
'unitPrice' => 190,
'cost' => 90,
'trackStockLevel' => true,
'isParentProduct' => false,
),
1 =>
array (
'id' => '5db29b6d31c391731239bbdb',
'name' => 'Long-sleeved shirt(sample)(M)',
'tags' =>
array (
0 => 'tops',
1 => 'cotton',
),
'category' => 'Women\'s Apparel',
'sku' => 'ABC1234-M',
'priceType' => 'Fixed',
'unitPrice' => 47.170000000000002,
'cost' => 20,
'trackStockLevel' => true,
'isParentProduct' => false,
'parentProductId' => '5db29b6d31c391731239bbd4',
'variationValues' =>
array (
0 =>
array (
'variantGroupId' => '5db29b6d31c391731239bbd5',
'value' => 'M',
),
),
),
)
note that the array can have many instances of product_name and sku, or can have none.
How do i populate this in my string to be like;
$content = "Your store, at location A, has these items added to them, 1) asd, 2)def, 3)asf . Do take note!
Try this, I've used \sprintf for ease, check if the output serves your purpose.
<?php
function stringMethod(): string
{
$count = 0;
$arrayString = [];
$array = [['product_name' => 'abc', 'product_sku' => 'def'],['product_name' => 'abc', 'product_sku' => 'asd']];
foreach ($array as $value){
$count++;
$arrayString[] = sprintf('%s)%s', $count, $value['product_sku']);
}
$string = \implode(',', $arrayString);
return \sprintf("Your store, at location A, has these items added to them %s Do take note!", $string);
}
echo stringMethod();
Hope this will help you. try to do it in less number of lines
$content = "Your store, at location A, has these items added to them, ";
$productArray = array (0 => array ('id' => '5db29b6d31c391731239bbdf','name' => 'Diamond bracelet (sample)','tags' => array (0 => 'female',1 => 'jewelry',),'category' => 'Accessories','sku' => '1029EHW','priceType' => 'Fixed','unitPrice' => 190,'cost' => 90,'trackStockLevel' => true,'isParentProduct' => false,),1 => array ('id' => '5db29b6d31c391731239bbdb','name' => 'Long-sleeved shirt(sample)(M)','tags' => array (0 => 'tops',1 => 'cotton',),'category' => 'Women\'s Apparel','sku' => 'ABC1234-M','priceType' => 'Fixed','unitPrice' => 47.170000000000002,'cost' => 20,'trackStockLevel' => true,'isParentProduct' => false,'parentProductId' => '5db29b6d31c391731239bbd4','variationValues' => array (0 => array ('variantGroupId' => '5db29b6d31c391731239bbd5','value' => 'M'))));
foreach ($productArray as $key => $product) {
$content .= ($key+1).') '.$product['name'];
if (count($productArray)-1!=$key) {
$content .= ', ';
}
}
$content .= ". Do take note!";
$content = "Your store, at location A, has these items added to them,". $this->getItemList($collection) .". Do take note!"
# Somewhere else in the controller
protected function getItemList(Collection $collection): string
{
return $collection->pluck('name')
->merge($collection->pluck('sku'))
->map(function($item, $key) {
return ($key + 1) . ') ' . $item;
})
->implode(', ');
}
An easy solution would be
$content = "Your store, at location A, has these items added to them";
$array = array(0=>["product_name" => "abc", "product_sku" => "def"], 1=>['product_name' => 'kdkf', 'product_sku'=> 'ljbkj']);
for($i = 0; $i<count($array); $i++){
$content .= ($i+1).") ".$array[$i]['product_name].' '.$array[$i]['product_sku'].', ';
}
$content .= "Do take note.";
This way you're just constantly concatonating the string value in separate parts instead of trying to inject it in the middle of the parent string.
not tested, may be syntax errors
I have a simple php array for location postcode and their name. I want compress 'code' by 'name'. This code from WooCommerce database zones.
$new_arr = [
[
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
],
[
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
],
[
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
],
[
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
]
];
I want get final result combined by 'name' and 'code' like this: i try array_unique method but not working.
Array (
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36139 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36127, 36129
[code_name] => 36127, 36129 - Bagan Pete
)
)
I try this method, but not fix at 'code_name'
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code'] . ' - ' . $value['name']
);
}
}
$out = array_values($out);
print_r($out);
You have to check duplicate name by in_array and update exist array value .If not exist insert that value to $out array .
$out = array();
foreach($new_arr as $k=>$v) {
//empty array state
if(count($out) == 0) {
$out[] = $v;
continue;
}
foreach ($out as $key => $value) {
if(in_array($v["name"],$value)) {
$out[$key]["code"] .= ",".$v["code"];
//for the code_name output as OP described
$nn = explode("-", $value["code_name"]);
$l = count($nn) - 1;
unset($nn[$l]);
$out[$key]["code_name"] = implode($nn).",".$v["code_name"];
break;
} else {
if((count($out)-1) == $key) {
$out[] = $v;
}
}
}
}
var_dump($out);
For someone have problem like me, this method for fix it:
$out = array();
foreach ($new_arr as $key => $value){
if (array_key_exists($value['name'], $out)){
$out[$value['name']]['code'] .= ', '.$value['code'];
$out[$value['name']]['code_name'] .= ', '.$value['code'] . ' - ' . $value['name'];
} else {
$out[$value['name']] = array(
'name' => $value['name'],
'code' => $value['code'],
'code_name' => $value['code']
);
}
}
$out = array_values($out);
print_r($out);
Final result;
Array
(
[0] => Array
(
[name] => Jambi Selatan
[code] => 36139, 36137
[code_name] => 36139, 36137 - Jambi Selatan
)
[1] => Array
(
[name] => Bagan Pete
[code] => 36129, 36127
[code_name] => 36129, 36127 - Bagan Pete
)
)
Please try below one as another approach:
<?php
$arr = Array (
Array
(
'name' => 'Jambi Selatan',
'code' => '36139',
'code_name' => '36139 - Jambi Selatan'
),
Array
(
'name' => 'Jambi Selatan',
'code' => '36137',
'code_name' => '36137 - Jambi Selatan'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36129',
'code_name' => '36129 - Bagan Pete'
),
Array
(
'name' => 'Bagan Pete',
'code' => '36127',
'code_name' => '36127 - Bagan Pete'
)
);
$newarr = array();
$finalArr = array();
foreach($arr as $aa) {
$newarr[$aa['name']][] = $aa;
}
foreach($newarr as $kk => $bb) {
foreach($bb as $cc) {
$finalArr[$kk]['name'] = $cc['name'];
if(isset($finalArr[$kk]['code'])) {
$finalArr[$kk]['code'] = $finalArr[$kk]['code'].','.$cc['code'];
} else {
$finalArr[$kk]['code'] = $cc['code'];
}
if(isset($finalArr[$kk]['code_name'])) {
$finalArr[$kk]['code_name'] = $finalArr[$kk]['code_name'].','.$cc['code_name'];
} else {
$finalArr[$kk]['code_name'] = $cc['code_name'];
}
}
}
echo "<pre>";
print_r($finalArr);
echo "</pre>";
?>
Definitely avoid any suggestions that use more than one loop to group and concatenate the data.
I do endorse #Opsional's snippet. An alternative approach is to push reference variables into the result array, then only concatenate comma-separated values to the appropriate reference variable.
Code: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($ref[$row['name']])) {
$ref[$row['name']] = $row;
$result[] = &$ref[$row['name']];
} else {
$ref[$row['name']]['code'] .= ', ' . $row['code'];
$ref[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export($result);
For any purist developers that insist on destroying references, call unset($ref) after the loop.
Here is a streamlined version of #Opsional's snippet: (Demo)
$result = [];
foreach ($arr as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['code'] .= ', ' . $row['code'];
$result[$row['name']]['code_name'] .= ', ' . $row['code_name'];
}
}
var_export(array_values($result));
I want to count all the values (The name of the cities) in this array who have the character t before the last character in the string.
ARRAY
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
The results should be: 3 (Paris_t1 - Madrid_t1 - Amsterdam_t1)
I believe i have to combine:
array_count_values($cities_array)
and
substr($value, -2, 1) == "t"
I have tried, but I get only errors.
This will give you what you want.
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$count = 0;
$city_text = '';
foreach($cities_array as $city){
if(substr($city, -2, 1) == "t"){
$count++;
$city_text .= $city . '-';
}
}
echo $count. "(".rtrim($city_text,'-').")";
Try below solution:
$cities_array = array(
"city1" => "Paris_t1",
"city2" => "Madrid_t1",
"city3" => "Amsterdam_t1",
"city4" => "London_i1",
"city5" => "Miami_i1",
"city6" => "Berlin_i1",
"city7" => "Brussels_i1",
"city8" => "Toronto_i1",
);
$filtered_array = array_filter($cities_array, function($val){
return (strpos($val, 't', (strlen($val)-2)) !== false);
});
print_r($filtered_array);
output: - (you can implode array by - to get desired result)
Array
(
[city1] => Paris_t1
[city2] => Madrid_t1
[city3] => Amsterdam_t1
)
In above solution in strpos third parameter strlen($val)-2) i.e. position will be searched from second last character of $val
I am having problem with session array variable
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
It automatically destroy when land on the other page, by using the <form action=”booking_level.php”>
foreach ( $arrRoomInfo as $arrRoomDetails ) {
// occup details
$AdultNum = ( int ) $arrRoomDetails->AdultNum;
$ChildNum = ( int ) $arrRoomDetails->ChildNum;
// child ages details
$strChAgs = '';
if (property_exists ( $arrRoomDetails, 'ChildAges' )) {
$childAgs = $arrRoomDetails->ChildAges->ChildAge;
$arrChAge = array ();
foreach ( $childAgs as $chAgs ) {
$chAgs = $chAgs->attributes ();
$arrChAge [] = $chAgs ['age'];
}
$strChAgs = implode ( ":", $arrChAge );
}
// set array for all the above details
$strRTypeArr [$rtId] [$i] = array (
'myRoomSq' => $i,
'roomSeq' => $arrRmSeq,
'adults' => $AdultNum,
'child' => $ChildNum,
'childAges' => $strChAgs,
'maxGuests' => $maxGuests,
'maxChild' => $maxChild,
'name' => $rmName,
'HotelRoomTypeId' => $rtId,
'roomId' => $roomId,
'isPublish' => $isPublish,
'Occupancy' => array (
"attributes" => array (
'avrNgtlyRtComm' => $avrNgtlyRtComm,
'avrNightPrice' => $avrNtPr,
'bedding' => $bedding
),
"boardBase" => array (
'bbId' => $arrBrdBsId,
'bbName' => $arrBrdBsName,
'bbPrice' => $arrBrdBsPrice,
'bbPublishPrice' => $arrBrdBspBPrce,
'strBBaseExists' => $strBBaseExists
),
'PriceBreakdown' => $arrDay,
"dblBrDownPrTourico" => $dblBrDownPrTourico,
"dblTtlBrDownPr" => $dblTtlBrDownPr,
'Supplements' => $arrSupp
),
'Discount' => $arrDst,
'cancelPolicy' => $strCnlionHtml,
'arrCanPolicy' => $arrCanPolicy,
'arrChcrCanPolicy' => $arrChcrCanPolicy,
'chcr_cancelPolicy' => $chcrCancellation,
'curncy' => $strCurn
);
$i ++;
}
}
}
}
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
How can I store in Session Array Variable in a MySQL database ?
Just make sure that you assign the array the way you assign a normal value and then store the array in your database.
$_SESSION['dArray'] = $strRTypeArr;
//for example:
$strRTypeArr[0][0] = array (
'myRoomSq' => 2.5,
'roomSeq' => "test this",
'adults' => true,
'child' => 5,
'childAges' => "test"
);
$strRTypeArr[0][1] = array (
'myRoomSq' => 3.5,
'roomSeq' => "this is another test",
'adults' => false,
'child' => 6,
'childAges' => "test"
);
$_SESSION['dArray'] = $strRTypeArr;
echo "<pre>";
print_r($_SESSION['dArray']);
echo "</pre>";
//Store this $_SESSION['dArray'] in your database
You can also use json_encode($_SESSION['dArray']); to store your array in the database.
I'm in PHP and I've got an array that looks like this. A single dimension array whose keys are bracketed strings.
array(
'matrix[min_rows]' => '0',
'matrix[max_rows]' => '',
'matrix[col_order][]' => 'col_new_1',
'matrix[cols][col_new_0][type]' => 'text',
'matrix[cols][col_new_1][type]' => 'text',
'matrix[cols][col_new_0][label]' => 'Cell 1',
'matrix[cols][col_new_1][label]' => 'Cell 2',
'matrix[cols][col_new_0][name]' => 'cell_1',
'matrix[cols][col_new_1][name]' => 'cell_2',
'matrix[cols][col_new_0][instructions]' => '',
'matrix[cols][col_new_1][instructions]' => '',
'matrix[cols][col_new_0][width]' => '33%',
'matrix[cols][col_new_1][width]' => '',
'matrix[cols][col_new_0][settings][maxl]' => '',
'matrix[cols][col_new_0][settings][fmt]' => 'none',
'matrix[cols][col_new_0][settings][content]' => 'all',
'matrix[cols][col_new_1][settings][maxl]' => '140',
'matrix[cols][col_new_1][settings][multiline]' => 'y',
'matrix[cols][col_new_1][settings][fmt]' => 'none',
'matrix[cols][col_new_1][settings][content]' => 'all',
)
Is there any easy way to convert that to a normal nested array, ie:
array(
'matrix' => array(
'min_rows' => '0',
'max_rows' => '',
'col_order' => array('col_new_1'),
'cols' => array(
'col_new_0' => array(
'type' => 'text',
'label' => 'Cell 1',
....etc....
This is my current solution, but I was wondering if there's something more native or efficient:
foreach ($decoded_field_type_settings as $key => $value)
{
if (preg_match_all('/\[(.*?)\]/', $key, $matches))
{
$new_key = substr($key, 0, strpos($key, '['));
if ( ! isset($field_type_settings[$new_key]))
{
$field_type_settings[$new_key] = array();
}
$array =& $field_type_settings[$new_key];
$count = count($matches[1]) - 1;
foreach ($matches[1] as $i => $sub_key)
{
if ( ! $sub_key)
{
if ($i < $count)
{
$array[] = array();
}
else
{
$array[] = $value;
}
}
else
{
if ( ! isset($array[$sub_key]))
{
if ($i < $count)
{
$array[$sub_key] = array();
}
else
{
$array[$sub_key] = $value;
}
}
}
if ($i < $count)
{
$array =& $array[$sub_key];
}
}
}
else
{
$field_type_settings[$key] = $value;
}
}
UPDATE: I posted an answer below.
This might work, although it would probably generate some warnings:
$matrix = array();
foreach($arr as $key => $value) {
eval('$' . $key . ' = \'' . $value . '\';');
}
var_dump($matrix);
I think this should do it...
<?php
function convert2dTo3d($source) {
$refs = array();
$output = array();
foreach ($source AS $key => $val) {
$tok = strtok($key, '[]');
$prev_tok = NULL;
while ($tok !== FALSE) {
$this_ref =& $refs[$tok];
if ($prev_tok === NULL)
$output[$tok] =& $this_ref;
else
$refs[$prev_tok][$tok] =& $this_ref;
$prev_tok = $tok;
$tok = strtok('[]');
if ($tok === FALSE)
$refs[$prev_tok] = $val;
}
}
return $output;
}
// Test
$source = array(
'matrix[min_rows]' => '0',
'matrix[max_rows]' => '',
'matrix[col_order][]' => 'col_new_1',
'matrix[cols][col_new_0][type]' => 'text',
'matrix[cols][col_new_1][type]' => 'text',
'matrix[cols][col_new_0][label]' => 'Cell 1',
'matrix[cols][col_new_1][label]' => 'Cell 2',
'matrix[cols][col_new_0][name]' => 'cell_1',
'matrix[cols][col_new_1][name]' => 'cell_2',
'matrix[cols][col_new_0][instructions]' => '',
'matrix[cols][col_new_1][instructions]' => '',
'matrix[cols][col_new_0][width]' => '33%',
'matrix[cols][col_new_1][width]' => '',
'matrix[cols][col_new_0][settings][maxl]' => '',
'matrix[cols][col_new_0][settings][fmt]' => 'none',
'matrix[cols][col_new_0][settings][content]' => 'all',
'matrix[cols][col_new_1][settings][maxl]' => '140',
'matrix[cols][col_new_1][settings][multiline]' => 'y',
'matrix[cols][col_new_1][settings][fmt]' => 'none',
'matrix[cols][col_new_1][settings][content]' => 'all',
);
echo "<pre>";
print_r(convert2dTo3d($source));
echo "</pre>";
It seems that the OP wants, as output, an array declaration which can be parsed directly by PHP. So I suggest to use var_export().
$array = array(
'matrix[min_rows]' => '0',
// ......
// ......
// ......
'matrix[cols][col_new_1][settings][content]' => 'all'
);
$matrix = array();
foreach ($array as $key => $value)
{
// fix missing quotes around array indexes
$key = str_replace(array("[", "]", "['']"), array("['", "']", "[]"), $key);
// fill PHP array
eval('$'.$key.' = $value;');
}
var_export($matrix);
You can make use of a simple, regular expression based parser that creates a multidimensional array based on the information stored in the string per each key:
function parse_flat_matrix(array $flat)
{
$matrix = array();
$varname = 'matrix';
$nameToken = '[a-z0-9_]*';
foreach($flat as $key => $value)
{
$keys = preg_split(sprintf('/(\[%s\])/', $nameToken), $key, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if ($varname !== array_shift($keys))
{
throw new InvalidArgumentException(sprintf('Invalid key %s.', $key));
}
$p =& $matrix;
foreach($keys as $k)
{
$r = preg_match(sprintf('/^\[(%s)\]$/', $nameToken), $k, $kk);
if (!$r)
{
throw new InvalidArgumentException(sprintf('Invalid subkey %s in key %s.', $k, $key));
}
if ('' === $kk[1])
{
$p =& $p[];
}
else
{
$p =& $p[$kk[1]];
}
}
$p = $value;
unset($p);
}
return $matrix;
}
With your example data given, it will create this array:
Array
(
[min_rows] => 0
[max_rows] =>
[col_order] => Array
(
[0] => col_new_1
)
[cols] => Array
(
[col_new_0] => Array
(
[type] => text
[label] => Cell 1
[name] => cell_1
[instructions] =>
[width] => 33%
[settings] => Array
(
[maxl] =>
[fmt] => none
[content] => all
)
)
[col_new_1] => Array
(
[type] => text
[label] => Cell 2
[name] => cell_2
[instructions] =>
[width] =>
[settings] => Array
(
[maxl] => 140
[multiline] => y
[fmt] => none
[content] => all
)
)
)
)
This was the simplest solution, involving no regex parsing:
$original_array = array(
'matrix[min_rows]' => '0',
'matrix[max_rows]' => '',
'matrix[col_order][]' => 'col_new_1',
'matrix[cols][col_new_0][type]' => 'text',
'matrix[cols][col_new_1][type]' => 'text',
'matrix[cols][col_new_0][label]' => 'Cell 1',
'matrix[cols][col_new_1][label]' => 'Cell 2',
'matrix[cols][col_new_0][name]' => 'cell_1',
'matrix[cols][col_new_1][name]' => 'cell_2',
'matrix[cols][col_new_0][instructions]' => '',
'matrix[cols][col_new_1][instructions]' => '',
'matrix[cols][col_new_0][width]' => '33%',
'matrix[cols][col_new_1][width]' => '',
'matrix[cols][col_new_0][settings][maxl]' => '',
'matrix[cols][col_new_0][settings][fmt]' => 'none',
'matrix[cols][col_new_0][settings][content]' => 'all',
'matrix[cols][col_new_1][settings][maxl]' => '140',
'matrix[cols][col_new_1][settings][multiline]' => 'y',
'matrix[cols][col_new_1][settings][fmt]' => 'none',
'matrix[cols][col_new_1][settings][content]' => 'all',
);
$query_string = http_build_query($original_array);
$final_array = array();
parse_str($query_string, $final_array);
var_dump($final_array);