您好,我需要帮助。我是学生,我的php有问题。
我有这个数据结构:
array
[0] => array(3){
["type"]=>"fruits"
["name"]=>"banane"
["depends"]=>array(3){
[0]=>"fraise"
[1]=>"kiwi"
[2]=>"pomme"
}
}
[1] => array(3){
["type"]=>"fruits"
["name"]=>"ananas"
["depends"]=>array(3){
[0]=>"avocat"
[1]=>"kiwi"
[2]=>"banane"
}
}
[2] => array(3){
["type"]=>"fruits"
["name"]=>"kiwi"
["depends"]=>array(3){
[0]=>"ananas"
[1]=>"avocat"
[2]=>"banane"
}
}
...
首先,我需要一个像这样的名字数组:
array {
[0]=>"banane"
[1]=>"ananas"
...
}
对于我希望拥有的每个数组名称: //首先查看名称是否存在取决于
array {
["banane"] =>array{
[0]=>"ananas"
[1]=>"kiwi"
}
["ananas"] =>array{
[0]=>"kiwi"
}
}
对于我的第二个foreach,使用名字的每个儿子。查看depends
中是否存在名称并执行:
array {
["banane"] =>array{
[0]=>"ananas" =>array{
[0]=>"kiwi"
}
[1]=>"kiwi" =>array{
[0]=>"banane"
[1]=>"ananas"
}
}
["ananas"] =>array{
[0]=>"kiwi"
}
}
这是我执行此操作的代码
<?php
$json = file_get_contents("data/data.json");
$data = json_decode($json, true);
//create my liste of fruits
$fruits_liste = array_column($data, 'name');
$parcours = array();
foreach ($fruits_liste as $indice => $fruits_name) {
foreach ($data as $key => $value) {
if (in_array($fruits_name, $value['depends'])) {
$parcours[$fruits_name] = $value['name'];
}
}
}
echo '<pre>';
var_dump($parcours);
echo '</pre>';
我的var_dump
的结果array(3) {
["banane"]=>
string(4) "kiwi"
["ananas"]=>
string(4) "kiwi"
["kiwi"]=>
string(6) "ananas"
}
我的数据文件
[
{
"type" : "fruits",
"name" : "banane",
"depends" : [
"fraise",
"kiwi",
"pomme"
]
}, {
"type" : "fruits",
"name" : "ananas",
"depends" : [
"avocat",
"kiwi",
"banane"
]
}, {
"type" : "fruits",
"name" : "kiwi",
"depends" : [
"ananas",
"avocat",
"banane"
]
}
]