如何在php中创建多维数组?

时间:2022-08-27 18:08:51

I am trying to make a multidimensional array.

我在尝试做一个多维数组。

  $a = array(
        array(
            '1' => 'One',
            '2' => 'two'
        ),
        array(
            '3' => 'three',
            '4' => 'four'
        )
    );

    $query_array = array();
    foreach( $meta_keys as $meta_key ) {
        $query_ = array();
        foreach( $meta_key as $key ) {
            $query_['key1'] = 'val1';
            $query_['key2'] = 'val2';
            $query_['key3'] = $meta_key;    
        }
        array_push( $query_array, $query_ );
    }

That is I am trying. But no luck.

那就是我在努力。但没有运气。

I want an array so that it will be as below...

我想要一个数组,这样它就会在下面。

 $query_array = array(
    array(
        'key1'  => 'val1',
        'key2'  => 'val2',
        'key3'  => 'one' //only change here
    ),
    array(
        'key1'  => 'val1',
        'key2'  => 'val2',
        'key3'  => 'two' //only change here
    ),
    array(
        'key1'  => 'val1',
        'key2'  => 'val2',
        'key3'  => 'three' //only change here
    )
  // Goes here same until the first $a value is end.
);

I have used array_merge() and array_combine() function with different way in foreach loop. But no result. A great messed up result comes.

在foreach循环中,我使用了array_merge()和array_combine()函数。但是没有结果。一个糟糕的结果来了。

So how can I do that in php? Thanks

在php中怎么做呢?谢谢

1 个解决方案

#1


0  

Something like this should work :

像这样的东西应该可以:

$res = [];
array_walk_recursive($a, function($item) use ($res, $b){
    $b["key3"] = $item;
    res[] = $b;
});

It's untested.

这是未经检验的。

#1


0  

Something like this should work :

像这样的东西应该可以:

$res = [];
array_walk_recursive($a, function($item) use ($res, $b){
    $b["key3"] = $item;
    res[] = $b;
});

It's untested.

这是未经检验的。