Reputation: 37
I am trying to read from a file and store in a multidimensional array. My final array should look like that:
$products = [
"tshirt" => [
"color" => "red",
"designer" => "hisName",
"year" => "2000"
]
"pants" => [
"color" => "black,
"designer" => "hisName",
"year" => "2003"
]
]
I am confused since I am not getting how to specify where to store the data in the array.
here's my code:
<?php
$lignes = file('./file.txt');
$index = 0;
$indexId = 0;
foreach($lignes as $ligne){
$ligne = trim($ligne);
if($index == 0){
$id = $ligne;
$livres[$indexId] = $id;
$indexId++;
$index++;
}elseif($ligne != "+ + +"){
$livres[$id][] = $ligne;
}else{
$index = 0;
}
}
?>
And here's a preview of the content of file.txt:
type
color
designer
year
+ + +
type
color
designer
year
each entry is separated by + + +
Upvotes: 1
Views: 44
Reputation: 9273
Assuming the product, color, designer and year are always in that order:
<?php
for( $i=0; $i < sizeof( $lignes ); $i++ ){
$product = $lignes[ $i++ ];
$products[ $product ][ 'color' ] = $lignes[ $i++ ];
$products[ $product ][ 'designer' ] = $lignes[ $i++ ];
$products[ $product ][ 'year' ] = $lignes[ $i++ ];
}
Upvotes: 1
Reputation: 116
Your text file needs more information unless all the information is in a specific order... Somehow a key has to be tied to a value in the text file so I'm assuming every 1st element is the category and the elements after that are specific keys like color, etc. I mimicked your text file into an array .. this would happen with your file() statement... you can also use a switch() command but I tried to follow your code as closely as possibly.
<?php
$lignes = array('tshirt','red','hisName','2000','+ + +','pants','black','hisName','2003');
$index = 0;
$category = "";
$type = "";
foreach($lignes as $ligne){
$ligne = trim($ligne);
if($index == 0) { $category = $ligne; }
elseif ($index == 1) { $type = "color"; }
elseif ($index == 2) { $type = "designer"; }
elseif ($index == 3) { $type = "year"; }
elseif ($ligne == "+ + +") {
$index = -1;
$category = "";
$type = "";
}
$index++;
if ($category && $type) {
$livres[$category][$type] = $ligne;
}
}
print "<pre>";
print_r($livres);
print "</pre>";
?>
My result was:
Array
(
[tshirt] => Array
(
[color] => red
[designer] => hisName
[year] => 2000
)
[pants] => Array
(
[color] => black
[designer] => hisName
[year] => 2003
)
)
Upvotes: 1