I have an array like this :
array(3) {
[0]=>
array(2) {
[0]=>
string(6) "action"
[1]=>
string(5) "depot"
}
[1]=>
array(2) {
[0]=>
string(9) "Demandeur"
[1]=>
string(11) "Particulier"
}
[2]=>
array(2) {
[0]=>
string(3) "Nom"
[1]=>
string(6) "Cheval"
}
But I want an associative array, to access it like this : $_REQUEST['Nom'] and have in return 'Cheval' etc...
The first array is actually an object, created with jQuery and here is his construction :
jQuery('input:submit').click(function() {
var itemMetaArray = {};
jQuery('.frm_pro_form :input:not(:hidden, :submit)').each(function() {
if(jQuery('#field_demande').val() != undefined){
itemMetaArray['action'] = jQuery('#field_demande').val();
}
else itemMetaArray['action'] = jQuery('#field_demande2').val();
var label = jQuery(this).closest('.frm_form_field').find('.frm_primary_label').text().trim();
if(jQuery(this).attr('name').indexOf("file") == -1 ) {
itemMetaArray[label] = jQuery(this).val();
}else{
var fileName = jQuery(this).attr('name');
fileName = fileName.substring(0,fileName.length-2);
itemMetaArray[label] = fileName;
}
});
After this, I do some parsing in PHP :
$dataInfo = explode(",",$_POST['dataInfo']);
for ($i = 0; $i < count($dataInfo); ++$i){
$tmpWithoutBrackets[$i] = trim($dataInfo[$i],"{..}");
$tmpWithoutColon[$i] = explode(":",$tmpWithoutBrackets[$i]);
for($j = 0; $j < (count($tmpWithoutColon) + 1); ++$j){
$arrayFinal[$i][$j] = trim($tmpWithoutColon[$i][$j],"\"");
}
$arrayFinal[$i] = array_diff($arrayFinal[$i],array(""));
}
$arrayFinal is the same array as arrayInfo
Thanks in advance for your help
You need to modify your array like this:
$test = array('arrayInfo' => array(array('Nom','Cheval'),array('Prenom','Nathan'),array('Adresse postale','4 impasse Molinas')),'arrayFile' => array(array ('application/pdf','3a514fdbd3ca2af35bf8e5b9c3c80d17','JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhmci1GUikgL1N0cnVjdFRyZWVSb290IDI2IDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0cnVlPj4vTWV0')));
$result = array();
foreach($test as $k=>$t){
$count = 0;
$_key = '';
$_value = '';
foreach($t as $f){
foreach($f as $final){
$count++;
if($count%2!==0){
$_key = $final;
}
else{
$_value = $final;
}
if($_value!==''){
$result[$k][$_key] = $_value;
$_value = '';
}
}
}
}
echo $result['arrayInfo']['Nom'];//Cheval
For your modified question, answer will be a little changed ofcourse:
$test = array(array('Nom','Cheval'),array('Prenom','Nathan'),array('Adresse postale','4 impasse Molinas'));
$result = array();
foreach($test as $k=>$t){
$count = 0;
$_key = '';
$_value = '';
foreach($t as $final){
$count++;
if($count%2!==0){
$_key = $final;
}
else{
$_value = $final;
}
if($_value!==''){
$result[$_key] = $_value;
$_value = '';
}
}
}
var_dump($result);
echo $result['Nom'];//Cheval
I hope it helps
Related
Here is my problem..
I have Session with Array looking like this
array(3) { [0]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-10" } } [1]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-11" } } [2]=> array(1) { ["trailer"]=> array(1) { ["id"]=> string(5) "id-10" } } }
and an php method .. oh and 1 more thing, im using laravel 5.6
My Code:
public function updateTrailerViews($id = 1){
$trailerViews = array(array());
$trailerViewsCount = \Session::get('trailerViews') == NULL ? 1 : count(\Session::get('trailerViews'));
if($trailer['id'] == NULL){
$id = 1;
}
if (\Session::get('trailerViews') == NULL) {
for ($i=0; $i < $trailerViewsCount; $i++) {
$trailerViews[$i]['trailer']['id'] = 'id-'.$id;
//$trailer['views'] = $trailer['views']+1;
//$trailer->save();
}
\Session::put('trailerViews', $trailerViews);
}else{
for($i=0;$i<$trailerViewsCount;$i++){
if(\Session::get('trailerViews')[$i]['trailer']['id'] != 'id-'.$id){
$idNotExist = 'true';
}else{
$idNotExist = 'false';
}
}
if($idNotExist == 'true'){
$trailerViewsCount1 = $trailerViewsCount+1;
for($int=0;$int<$trailerViewsCount1;$int++){
if($int == $trailerViewsCount1-1){
// if is the last integer of the loop add the new record
$trailerViews[$int]['trailer']['id'] = 'id-'.$id;
}else{
for($int1 = 0; $int1 < $trailerViewsCount; $int1++){
// if the integer is not the last number of the loop add the previous records from the session
$trailerID = \Session::get('trailerViews')[$int1]['trailer']['id'];
$trailerViews[$int1]['trailer']['id'] = $trailerID;
}
}
\Session::put('trailerViews', $trailerViews);
}
}
}
$trailerViewsCountReturn = count(\Session::get('trailerViews'));
//$trailerViewsNumber = \AppHelper::instance()->short_number_format($trailer['views']);
return var_dump(\Session::get('trailerViews'));
}
The problem is when im trying to check the unique id of the page sometimes have a bug, when open page with id=2 then id=5 or other.. and again open id=2 the id is going to be added again.
I wanna make it with unique page id's only.
SOLVED!
public function updateTrailerViews($id = 1){
$trailer = Trailers::find($id);
$trailerViews = array(array());
$trailerViewsCount = \Session::get('trailerViews') == NULL ? 1 : count(\Session::get('trailerViews'));
if($trailer['id'] == NULL){
$id = 1;
}
if (\Session::get('trailerViews') == NULL) {
for ($i=0; $i < $trailerViewsCount; $i++) {
$trailerViews[$i] = 'id-'.$id;
$trailer['views'] = $trailer['views']+1;
$trailer->save();
}
\Session::put('trailerViews', $trailerViews);
}else{
if(!in_array('id-'.$id, \Session::get('trailerViews'))){
if($trailer['id'] == $id){
$idNotExist = 'true';
$trailer['views'] = $trailer['views']+1;
$trailer->save();
}else{
$idNotExist = 'false';
}
}else{
$idNotExist = 'false';
}
if($idNotExist == 'true'){
$trailerViewsCount1 = $trailerViewsCount+1;
for($int=0;$int<$trailerViewsCount1;$int++){
if($int == $trailerViewsCount1-1){
// if is the last integer of the loop add the new record
$trailerViews[$int] = 'id-'.$id;
}else{
for($int1 = 0; $int1 < $trailerViewsCount; $int1++){
// if the integer is not the last number of the loop add the previous records from the session
$trailerID = \Session::get('trailerViews')[$int1];
$trailerViews[$int1] = $trailerID;
}
}
$trailerViews = array_unique($trailerViews);
\Session::put('trailerViews', $trailerViews);
}
}
}
$trailerViewsCountReturn = count(\Session::get('trailerViews'));
$trailerViewsNumber = \AppHelper::instance()->short_number_format($trailer['views']);
return $trailerViewsNumber;
}
I am parsing a text file that looks more or less like this:
123.animal=cat
123.name=fred
123.food=fish
345.animal=dog
petshop=zoonoria
This is how I am parsing it:
$file_path = $filename;
$linesArray = file($file_path);
$properties = array();
foreach ($linesArray AS $line) {
if (strlen($line) && $line[0] == '#') {
$pdate = substr($line, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = trim($lineContArray[1]);
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found == 0) {
if (!empty($type)) {
$properties[] = array('number' => $ident, $type => $value);
} else {
$properties[] = array($ident => $value); }
}
}
My result is:
array(3) {
[0]=>
array(2) {
["number"]=>
string(3) "123"
["animal"]=>
string(3) "cat"
}
[1]=>
array(2) {
["number"]=>
string(3) "123"
["name"]=>
string(4) "fred"
}
[3]=>
array(2) {
["number"]=>
string(3) "345"
["animal"]=>
string(4) "dog"
}
[4]=>
array(1) {
["petshop"]=>
string(5) "zoonoria"
}
}
But I need the array to be different, this is the result I like to achieve:
array(3) {
[123]=>
array(3) {
["animal"]=>
string(3) "cat"
["name"]=>
string(4) "fred"
["food"]=>
string(4) "fish"
}
[345]=>
array(1) {
["animal"]=>
string(3) "dog"
}
[petshop]=>
string(8) "zoonoria"
}
}
So my main problem is, I do not know how to turn number into the key. I tried various things, but I failed. I am really happy for every hint.
I tried the solution of Svetlio:
$file_path = $filename;
$linesArray = file($file_path);
$properties = array();
foreach ( $linesArray as $str) {
$exp = explode ('=', $str);
if(count($exp) == 2){
$exp2 = explode('.', $exp[0]);
if( count($exp2) == 2 ) {
$properties [$exp2[0]][$exp2[1]] = $exp[1];
} else {
$properties [$exp[0]] = $exp[1];
}
} else {
}
}
My result:
array(3) {
["123"]=>
array(3) {
["animal"]=>
string(3) "cat
"
["name"]=>
string(4) "fred
"
["food"]=>
string(4) "fish
"
}
[345]=>
array(1) {
["animal"]=>
string(3) "dog
"
}
["petshop"]=>
string(3) "zoonoria
"
}
Here is working solution but it doesn't cover the cases where stings don't contain = or have more than 1 of them..
$strings = array(
'123.animal=cat',
'123.name=fred',
'123.food=fish',
'345.animal=dog',
'petshop=zoonoria'
);
$array = array();
foreach ( $strings as $str) {
// I accept that there is 1 = at strings possible
$exp = explode ('=', $str);
if(count($exp) == 2){
$exp2 = explode('.', $exp[0]);
if( count($exp2) == 2 ) {
$array[$exp2[0]][$exp2[1]] = $exp[1];
} else {
// if there are multiple/null dots i set the string as key
$array[$exp[0]] = $exp[1];
}
} else {
// what to do if there are no or many = = = in the string ?
}
}
var_dump($array);
After getting the result you can use array_reduce to get the desired result
$result = array_reduce($initialArray, function ($result, $item) {
$number = isset($item['number']) ? $item['number'] : end(array_keys($result));
if (!isset($result[$number])) {
$result[$number] = array();
}
foreach ($item as $key => $value) {
if ($key == 'number') continue;
$result[$number][$key] = $value;
}
return $result;
}, array());
foreach ($linesArray AS $line) {
if (strlen($line) && $line[0] == '#') {
$pdate = substr($line, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = trim($lineContArray[1]);
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found) {
if ($type && $ident) {
$properties[$ident][$type] = $value;
} else if (!$type && $ident) {
$properties[$ident][] = $value;
}else if ($type && !$ident){
$properties[$type][] = $value;
}
}
$data = '123.animal=cat
123.name=fred
123.food=fish
345.animal=dog
petshop=zoonoria';
$ini = parse_ini_string($data);
$result = [];
foreach ($ini as $key => $value) {
$splitKey = explode('.', $key);
$iniPtr = &$result;
foreach($splitKey as $subKey) {
if (!isset($iniPtr[$subKey])) { $iniPtr[$subKey] = null; }
$iniPtr = &$iniPtr[$subKey];
}
$iniPtr = $value;
}
unset($iniPtr);
var_dump($result);
Demo
In your case, use $ini = parse_ini_file($file_path); to read your file data into $ini
I have String array like below format
Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
I need result like below
Courses
- PHP
- Array
- Functions
- JAVA
- Strings
I used substr option to get result.
for($i=0;$i<count($outArray);$i++)
{
$strp = strrpos($outArray[$i], '/')+1;
$result[] = substr($outArray[$i], $strp);
}
But I didn't get result like tree structure.
How do I get result like tree structure.
Something like that?
$a = array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
$result = array();
foreach($a as $item){
$itemparts = explode("/", $item);
$last = &$result;
for($i=0; $i < count($itemparts); $i++){
$part = $itemparts[$i];
if($i+1 < count($itemparts))
$last = &$last[$part];
else
$last[$part] = array();
}
}
var_dump($result);
The result is:
array(1) {
["Courses"]=>
array(2) {
["PHP"]=>
array(2) {
["Array"]=>
array(0) {
}
["Functions"]=>
array(0) {
}
}
["JAVA"]=>
&array(1) {
["String"]=>
array(0) {
}
}
}
}
How about this one:
<?php
$outArray = Array(
"Courses",
"Courses/PHP",
"Courses/PHP/Array",
"Courses/PHP/Functions",
"Courses/JAVA",
"Courses/JAVA/String");
echo "-" . $outArray[0] . "<br/>";
for($i=0;$i<count($outArray) - 1;$i++)
{
create_tree($outArray[$i],$outArray[$i+1]);
}
function create_tree($prev, $arr)
{
$path1 = explode("/", $prev);
$path2 = explode("/", $arr);
if (count($path1) > count($path2))
echo str_repeat(" ",count($path1) - 1) . "-" . end($path2);
else
echo str_repeat(" ",count($path2) - 1) . "-" . end($path2);
echo $outArray[$i] . "<br/>";
}
Outputs:
-Courses
-PHP
-Array
-Functions
-JAVA
-Strings
I have the result below of 2 arrays starting with [0] what I am wanting to do is return a result of "2" - As I have 2 "strings". How would I do this?
Result:
Array(1) {
[0]=> string(32) "b5cfec3e70d0d57ea848d5d8b9f14d61"
}
Array(1) {
[0]=> string(32) "eda80a3d5b344bc40f3bc04f65b7a357"
}
PHP:
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$cartDataArray = explode(" ", $cartData);
$result = $cartDataArray;
var_dump($result);
}
If I got this right, I think this is what you want:
$count = 0;
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$result = count(explode(" ", $cartData));
$count += $result;
}
var_dump($count);
I'm trying to access the value ('Id') of an array.
This is my code to access the array:
$value[0]['Id']
This is the error: X
Cannot use string offset as an array
The array that I try to access: Y
array(1) { [0]=> array(1) { ["Id"]=> string(2) "42"} }
The surounding code
$query = "select Id from test where Tags = " . "\"$chosedOption[1]\"";
$result = mysql_query($query, $link);
$value = mysqlArray($result);
$value_id = null;
$value_id = $value[0]['Id']; // gives X
var_dump($value[0]['Id']);
var_dump($value); // gives Y
function mysqlArray($result) {
$table_result = array();
$r = 0;
while($row = mysql_fetch_assoc($result)) {
$arr_row = array();
$c = 0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result; }
Can it be that $value_id already has a (string) value?
Replace mysqlArray($result); with mysql_fetch_array($result);