Jump to content

[SOLVED] Take array values from file.


AbydosGater

Recommended Posts

Hey Guys,

Long time since i have done any php.

 

Just have to write a little script that opens a file and takes some values. There is an application that i use, it stores its Data in its own files, They are formatted like:

 

"IDCode"

{

"name" "Users Name"

"zomkh" "5"

"onekh" "6"

"humk1" "4"

"humkz" "7"

}

"IDCode2"

{

"name" "Users Name2"

"zomkh" "5"

"onekh" "6"

"humk1" "4"

"humkz" "7"

}

 

I was wondering if someone could please point me in the right direction on sorting this data into associative arrays please?

Any help would be greatly appriciated.

Link to comment
https://forums.phpfreaks.com/topic/105051-solved-take-array-values-from-file/
Share on other sites

that is literally what the input file looks like? a text file with lines like these?

 

   "IDCode"

   {

      "name"      "Users Name"

      "zomkh"      "5"

      "onekh"      "6"

      "humk1"      "4"

      "humkz"      "7"

   }

"IDCode2"

   {

      "name"      "Users Name2"

      "zomkh"      "5"

      "onekh"      "6"

      "humk1"      "4"

      "humkz"      "7"

   }

 

if so, i'd load all lines into an array and loop over the array applying logic to determine whether the line is 1. a single item, 2. a left or right bracket, or 3. two items. that would tell you what is an array name and what are it's keys/values (and what are brackets that should be ignored).

Not the best approach but it works:

<?php

$file_data = file_get_contents('file.txt');
$file_data = str_replace('"      "', ',', $file_data);
$file_data = preg_replace('|(\s+){2,}|', '', $file_data);
$file_data = preg_replace('|"([a-z0-9]+)"\{"|i', "$1|", $file_data);
$file_data = str_replace('""', '|', $file_data);
$file_data = str_replace('"}', "\n", $file_data);

$datas = explode("\n", $file_data);

foreach($datas as $data)
{
    $pieces = explode('|', $data);

    $idcode = array_shift($pieces);

    foreach($pieces as $attrs)
    {
        list($key, $value) = explode(',', $attrs);
        $codes[$idcode][$key] = $value;
    }
}

echo '<pre>' . print_r($codes, true) . '</pre>';

?>

The above code converts, the following line blocks such as:

"IDCode2"
   {
      "name"      "Users Name2"
      "zomkh"      "5"
      "onekh"      "6"
      "humk1"      "4"
      "humkz"      "7"
   }

to:

IDCode2|name,Users Name2|zomkh,5|onekh,6|humk1,4|humkz,7

Then uses a few simple loops to generate the $codes associative array

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.