联接2个多维数组 [英] Join 2 multidimensional array

查看:31
本文介绍了联接2个多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$items = array(
    array(
        'id' => 0,
        'name' => 'Simple Sword',
        'type' => 'weapon',
        'price' => 200,
        'value1' => 5,
        'value2' => 10,
        'value3' => 0,
        'value4' => 0,
        'value5' => 0
    ),
    array(
        'id' => 1,
        'name' => 'Iron Sword',
        'type' => 'weapon',
        'price' => 500,
        'value1' => 0,
        'value2' => 0,
        'value3' => 0,
        'value4' => 0,
        'value5' => 0
    )
);


$inventory = array(

    array(
        'item' => 0,
        'slot' => 1,
        'value1' => 0,
        'value2' => 0,
        'value3' => 0,
        'value4' => 0,
        'value5' => 0,
        'equipped' => 0
    ),

    array(
        'item' => 1,
        'slot' => 2,
        'value1' => 0,
        'value2' => 0,
        'value3' => 0,
        'value4' => 0,
        'value5' => 0,
        'equipped' => 1
    )  

);

我需要加入这2个多维数组,或从"Items"数组中获取值,键等,并将其放入"item" ID与Items数组中的ID匹配的Inventory数组中.与SQL中的INNER JOIN语句类似.如何?我不知道.

What I need is to join these 2 multidimensional arrays, or take the values, keys etc from the "Items" array and put it in the Inventory array where the "item" id matches the id from the Items array. Similiar to a INNER JOIN statement in SQL. How? I can't figure it out.

其次,我试图打印$ inventory数组,我尝试了以下操作,但是没有用:

Secondly, I am trying to print out the $inventory array, I tried the following, but It didn't work:

foreach ($inventory as $a) {

    foreach ($a as $b) {

        echo $b['item'];

    }

}

它没有输出.

推荐答案

foreach($inventory as $key=>$val)
{
    if($val['item'] == $items[$key]['id'])
    {
        $newarr[] = array_merge($items[$key],$val);
    }
}

使用 print_r($ newarr)检查 $ newarr [] ,此处为输出:

check $newarr[] using print_r($newarr), here the output :

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Simple Sword
            [type] => weapon
            [price] => 200
            [value1] => 0
            [value2] => 0
            [value3] => 0
            [value4] => 0
            [value5] => 0
            [item] => 0
            [slot] => 1
            [equipped] => 0
        )

    [1] => Array
        (
            [id] => 1
            [name] => Iron Sword
            [type] => weapon
            [price] => 500
            [value1] => 0
            [value2] => 0
            [value3] => 0
            [value4] => 0
            [value5] => 0
            [item] => 1
            [slot] => 2
            [equipped] => 1
        )

)

第二个问题,以打印出 $ inventory 数组:

Second question, to print out the $inventory array:

foreach ($inventory as $a) 
{
    echo $a['item'];
    echo $a['slot'];
    echo $a['value1'];
    //...etc
}

这篇关于联接2个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆