简体   繁体   English

如何使用数组作为数据库?

[英]How to use an array as data base?

    $travels = [
    0 => ['departure' => 'Paris', 'arrival' => 'Nantes'],
    1 => ['departure' => 'Orleans', 'arrival' => 'Nantes'],
    2 => ['departure' => 'Dublin', 'arrival' => 'Tours'],
    3 => ['departure' => 'Paris', 'arrival' => 'Orleans'],
    4 => ['departure' => 'Paris', 'arrival' => 'Nice'],
    5 => ['departure' => 'Nice', 'arrival' => 'Nantes'],
    6 => ['departure' => 'Nice', 'arrival' => 'Tours'],
    7 => ['departure' => 'Tours', 'arrival' => 'Amboise'],
    8 => ['departure' => 'Nice', 'arrival' => 'Nantes'],
];

So this is my code, I want to use this multiple array as a data base, but there is no queries right? 这是我的代码,我想将此多重数组用作数据库,但是没有查询吗?

So, I simply want to get all the arrivals values from one departure, like all the arrivals starting from paris, i've tried many things with foreach loop inside foreachloop and if statments and to use the index array but no chance. 因此,我只是想从一个出发点获得所有到达值,就像所有从巴黎出发的到达值一样,我已经尝试了在foreachloop内使用foreach循环和if语句进行许多操作,并使用索引数组,但没有机会。 Is there any way to do it like a query in mysql. 有没有办法像在mysql中一样进行查询。

Would be something like: 将是这样的:

"SELECT 'arrival' FROM 'travels' WHERE 'departure' = Paris"

As far as I understood your question, you could do something like this: 据我了解您的问题,您可以执行以下操作:

$resultArr = [];

array_walk($travels, function($value, $key) use (&$resultArr) {
    if($value['departure'] == 'Paris')
       $resultArr[$key] = $value;
});

This will fill your new array with those departures, that are only from Paris. 这将使您的新航班充满只有巴黎出发的航班。

Another approach would be the use of array_filter as suggested by mfonda in his answer of a post: 另一种方法是使用array_filter由mfonda在他的建议答复后的:

$filtered = array_filter($travels, function($v) { return $v['departure'] == 'Paris'; });

This will get all arrivals with departure 'Paris': 这将使所有从巴黎出发的到达者:

<?php
$travels = [
  0 => ['departure' => 'Paris', 'arrival' => 'Nantes'],
  1 => ['departure' => 'Orleans', 'arrival' => 'Nantes'],
  2 => ['departure' => 'Dublin', 'arrival' => 'Tours'],
  3 => ['departure' => 'Paris', 'arrival' => 'Orleans'],
  4 => ['departure' => 'Paris', 'arrival' => 'Nice'],
  5 => ['departure' => 'Nice', 'arrival' => 'Nantes'],
  6 => ['departure' => 'Nice', 'arrival' => 'Tours'],
  7 => ['departure' => 'Tours', 'arrival' => 'Amboise'],
  8 => ['departure' => 'Nice', 'arrival' => 'Nantes'],
];
foreach ($travels as $key => $value) {
    if ($value['departure'] == 'Paris') {
        echo $value['arrival'];
}
}
?>

This will list all the arrivals, however, if you want to limit to only show the arrival name once, you'll have to add some code. 这将列出所有到达者,但是,如果您想限制只显示一次到达者名称,则必须添加一些代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM