将类似的数组信息合并到Json中

时间:2016-02-26 21:29:04

标签: php arrays json

我有两个不同的Json文件,每个文件都是从不同的php数组生成的。它们都包含一条我想在一个文档中链接在一起的类似信息。

Php array one看起来像这样:

$HisNameIsMyName = array(
    'His' => 'John',
    'Name' => 'Jacob',
    'Is' => 'Jacob',
    'My' => 'Jacob',
    'Name2' => 'Shmidt');

并通过以下代码转换为Json

$compiled = json_decode(file_get_contents('compiled.json'), true);
foreach ($HisNameIsMyName as $word => $publisher) {
    $compiled[$word]['publisher'] = $publisher;
}
file_put_contents('compiled.json', json_encode($compiled, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

输出以下内容:

{
    "His": {
        "publisher": "John"
    },
    "Name": {
        "publisher": "Jacob"
    },
    "Is": {
        "publisher": "Jacob"
    },
    "My": {
        "publisher": "Jacob"
    },
    "Name2": {
        "publisher": "Shmidt"
    }
}

每个Publisher都在不同的数组中分配了一个数字,如下所示:

$numberToPublisher = array(
    "John" => 1,
    "Jacob" => 2,
    "Jingle" => 3,
    "Himer" => 4,
    "Shmidt" => 5

如何将Publisher中分配给$numberToPublisher的号码添加到Json,以便它看起来如下所示:

{
    "His": {
        "publisher": "John"
        "pubNumber": "1"
    },
    "Name": {
        "publisher": "Jacob"
        "pubNumber": "2"
    },
    "Is": {
        "publisher": "Jacob"
        "pubNumber": "2"
    },
    "My": {
        "publisher": "Jacob"
        "pubNumber": "2"
    },
    "Name2": {
        "publisher": "Shmidt"
        "pubNumber": "5"
    }
}

1 个答案:

答案 0 :(得分:1)

像这样扩展你现有的循环:

foreach ($HisNameIsMyName as $word => $publisher) {
    $compiled[$word]['publisher'] = $publisher;
    $compiled[$word]['pubNumber'] = $numberToPublisher[$publisher];
}