Z
Z
zdiii2014-06-21 22:01:23
PHP
zdiii, 2014-06-21 22:01:23

PHP: Array_column. How to output data from txt file to array_column?

Good night!)
Please help)
There is a text editor.
Example:
bd156d38fc5449e88911dfcab0bd12d2.png
It is necessary to display data from this in array_column Like
this:

$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

Please show examples)
Thank you for your attention)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mykola, 2014-06-21
@zdiii

Throwed on the knee

<?php
$array = array();
$lines = file('you_file.txt');
foreach ($lines as $value){
    $i = explode(' ', trim($value)); //
    $array[] = array('id' => "$i[0]", 'first_name' => "$i[1]", 'last_name' => "$i[2]");
}
var_dump($array);
?>

5495980.png

B
BoneFletcher, 2014-06-22
@BoneFletcher

$result = [];
$file = file_get_contents('file.txt');
$rows = explode('\n', $file);
$titles = explode('\t', array_shift($rows));
foreach ($rows as $row) {
    $cols = explode('\t', $row);
    for ($i=0; $i<count($titles); $i++) {
        if (isset($cols[$i])) {
            $cols[$titles[$i]] = $cols[$i];
            unset($cols[$i]);
        }
    }
    $result[] = $cols;
}

$first_names = array_column($result, 'first_name');
print_r($first_names);

S
Sergey Petrov, 2014-06-22
@sergoslav_0

In such cases, I use the fgetcsv function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question