K
K
KorLagar2020-04-19 15:36:49
PHP
KorLagar, 2020-04-19 15:36:49

Question on arrays, how to create according to given criteria?

Hello everyone, I encountered such a problem while learning php, tell me the solution.
It is necessary to create a single $data array, and come up with its structure in such a way that it would be convenient to store information on authors and books in the library.

For a book, you need to store the following information: Title, Year of issue.
For the author, you need to store the following information about him: Name, Email, Year of birth

The set of fields may expand in the future.

It is required to fill this array with at least 3 authors and 5 books.

Print the following information on the site:

1. Print the string: === Books ===
2. Print all the books on the site. Each book should be on a separate line, and the output format should be as follows:

Book title - Author's name - the year the book was published.

3. Print the string: === Authors ===
2. Print all the authors on the site. Each author should be on a separate line, while the output format should be as follows:

Author's name - his email - his year of birth.

For example:
=== Books ===
Dead Souls - Nikolay Vasilyevich - 1841
Viy - Nikolai Vasilyevich - 1834
The Queen of Spades - Pushkin - 1833

=== Authors ===
Nikolay Vasilyevich - [email protected] - 1809
Pushkin - [email protected] .ru - 1799

To solve the problem, it is forbidden to use functions, anonymous functions, type conversion, classes, database, other variables, except for $data.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikidze, 2020-04-19
@Nikidze

The task is trivial, if the solution is tight - I have bad news for you.

<?php
$data = array(
        'books' => [],
        'authors' => []
    );

function addAuthor($name, $email, $db){
    global $data;
    $data['authors'][] = array('name' => $name, 'email' => $email, 'db' => $db);
};
function addBook($title, $authorId, $year){
    global $data;
    $data['books'][] = array('title' => $title, 'author' => &$data['authors'][$authorId], 'year' => $year);
};

addAuthor('Пушкин', 'почта@пушкина', '1799'); // id = 0
addAuthor('Гоголь', 'почта@гоголя', '1809'); // id = 1

addBook('Вий', 1, 1834);
addBook('Другая книга Гоголя', 1, 1835);
addBook('А эту написал Пушкин', 0, 1820);

echo "===========Книги===============";
foreach($data['books'] as $book){
    echo $book['title'].' - '.$book['author']['name'].' - '.$book['year'].'<br>';
}
echo '===========Авторы===============';
foreach($data['authors'] as $authors){
    echo $authors['name'].' - '.$authors['email'].' - '.$authors['db'].'<br>';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question