将Python代码转换为PHP并附带参考问题

2024-04-30 19:50:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一些python代码转换成PHP,但要获得相同的输出有些困难。 实际上,我认为问题在于如何在Python中通过引用使用字典,而在PHP中更难

下面是我的Python代码:

import json
from pprint import pprint
a=["/",
"/page1.html",
"/cocktails/receipe/page1.html",
"/cocktails/receipe/page2.html",
"/cocktails/page3.html",
"/article/magazine",
"/article/mood/page1.html"]

def create(path,dictionaryandarray):
    #print(path[0],dictionary)
    if not path:
        return
    for ele in dictionaryandarray:
        if 'name' in ele and ele['name'] == path[0]:
            ele.setdefault('children',[])
            if (path[1:]):
                create(path[1:],ele['children'])
            return
    newvalue={'name':path[0]}
    if (path[1:]):
        newvalue['children']=[]

    dictionaryandarray.append(newvalue)
    if (path[1:]):
        create(path[1:], dictionaryandarray[-1]['children'])
d = []
for i in a:
    parts = [j for j in i.split('/') if j != '']
    create(parts ,d)

data={'name':'/','children':d}
data=json.dumps(data, indent=4, sort_keys=False)
# pprint(data)
print(data)

下面是我的PHP代码:

    <?php
$rows=[
"page1.html",
"/cocktails/receipe/page1.html",
"/cocktails/receipe/page2.html",
"/cocktails/page3.html",
"/article/magazine",
"/article/mood/page1.html"];

$res = [];
$i=0;
foreach($rows as $row){

    $suffix = preg_replace("#https?://[^/]*#", "", $row);

    $parts = array_values(array_filter(preg_split("#[/\?]#", $suffix)));
    create($parts, $res);    
}

$data=['name' => '/','children' =>$res];

$data= json_encode($data, true);

header('Content-Type: application/json');
echo $data;

function create($path, &$res){

    if (empty($path))
        return;


    if (is_null($res))
        return;

    foreach ($res as $key => $ele){

        if (array_key_exists("name", $ele) && $ele['name'] == $path[0]){
            if (!array_key_exists("children", $ele)){
                $res[$key]['children'] = [];
            }

            if (count($path) > 1){
                create(array_slice($path, 1), $res[$key]['children']);
            }
            return;
        }
    }

    $newvalue = ["name" => $path[0]];
    if (count($path)>1){
        $newvalue['children'] = [];
    }
    $res[] = $newvalue;
    if (count($path)> 1){
        create(array_slice($path, 1), end($res)['children']);
    }
}

我得到的是$res变量没有像python那样填充。我试图通过引用来传递它,但得到了相同的问题

也许有一种方法可以像Python那样填充它,但是我不知道怎么做

谢谢你的帮助


Tags: pathkeynamedatareturnifhtmlcreate
1条回答
网友
1楼 · 发布于 2024-04-30 19:50:39

PHP的foreach实现为按值调用,而不是按引用调用。所以你的$ele['children']作业什么也没做。而且,混合使用return和passbyreference也没有帮助

您可以将create()转换为完全引用样式,如下所示:

<?php

function create($path, &$res){

    if (empty($path))
        return;


    if (is_null($res))
        return;

    foreach ($res as $key => $ele){

        if (array_key_exists("name", $ele) && $ele['name'] == $path[0]){
            if (!array_key_exists("children", $ele)){
                $res[$key]['children'] = [];
            }

            if (count($path) > 1){
                create(array_slice($path, 1), $res[$key]['children']);
            }
            return;
        }
    }

    $newvalue = ["name" => $path[0]];
    if (count($path)>1){
        $newvalue['children'] = [];
    }
    $res[] = $newvalue;
    if (count($path)> 1){
        create(array_slice($path, 1), end($res)['children']);
    }
}

然后您应该简单地将$res = create($parts, $res);重写为create($parts, $res);。事情应该会成功的

相关问题 更多 >