我有三个数组:源、目标和费用。我想收取特定来源和目的地的费用

source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"];

destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"];

prices = ["500","300","400","600","500","500"];

我有源变量和目标变量:src="hyderabad" & des="mumbai"


我想从价格数组中获得从海得拉巴到孟买的 400 的价格。


我怎样才能得到这个?


素胚勾勒不出你
浏览 167回答 4
4回答

波斯汪

您可以使用 foreach 循环执行此操作:$source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"];$destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"];$prices = ["500","300","400","600","500","500"];foreach($prices as $key => $price) {&nbsp; // Array keys as string for source and destination.&nbsp; $srcToDest = $source[$key] . " -> " . $destination[$key];&nbsp; $charges[$srcToDest] = $price;}echo "<pre>"; print_r($charges);输出将是:Array(&nbsp; &nbsp; [hyderabd -> pune] => 500&nbsp; &nbsp; [banglore -> chennai] => 300&nbsp; &nbsp; [hyderabad -> mumbai] => 400&nbsp; &nbsp; [chennai -> hyderabad] => 600&nbsp; &nbsp; [pune -> banglore] => 500&nbsp; &nbsp; [mumbai -> hyderabad] => 500)

慕少森

如果您可以控制来源、目的地和价格,您可能应该以不同的格式存储它们,而不是三个单独的数组。您可能可以这样存储:$prices[$source][$destination] = $price;因此,根据您的输入,这将变为:$prices['hyderabad']['pune'] = 500;$prices['hyderabad']['mumbai'] = 400;$prices['banglore']['chennai'] = 300;$prices['chennai']['hyderabad'] = 600;$prices['pune']['banglore'] = 500;$prices['mumbai']['hyderabad'] = 500;

泛舟湖上清波郎朗

你可以做这样的事情来找到一个元素的索引echo&nbsp;$prices[array_search("hyderabad",&nbsp;$source)];&nbsp;//&nbsp;400然而,这似乎相当随机。如果源条目和目标条目的索引与价格不同,会发生什么情况?来源和目的地与价格有何关系?你到底想在这里实现什么?

墨色风雨

使用 array_column() 你得到你的结果$all[]=$source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"];$all[]=$destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"];$all[]=$prices = ["500","300","400","600","500","500"];$search =&nbsp; &nbsp;array_column($all, '2');print_r($search);?>````
打开App,查看更多内容
随时随地看视频慕课网APP