是否可以在php的索引数组中转换关联数组?

时间:2019-06-12 21:15:53

标签: php arrays chart.js

我有一个关联数组,我正在尝试使用它们的值,访问它们没有问题,我需要此值来生成图形,但是我不能使用它们,因为数据具有此结构public interface NotificationRepository extends MongoRepository<Notification, ObjectId> { ,但是生成图形的正确结构是{key1: 12.2, key2: 11.2, key3: 21.3}

我用来存储数据的数组如下

[12.2, 11.2, 21.3]

所以我认为,正如我所想的那样,问题是因为它是一个关联数组。

我遇到的解决方案是将关联数组转换为索引索引,我尝试通过以下方式实现

Array
(
[0] => Array
    (
        [key1] => 22.58
        [key2] => 27.91
        [key3] => 31.95
        [key4] => 36.32
        [key5] => 41.73
        [key6] => 45.78
        [key7] => 48.55
        [key8] => 53.48
        [key9] => 47.82
    )

[1] => Array
    (
        [key1] => 20.94
        [key2] => 27.36
        [key3] => 32.12
        [key4] => 36.33
        [key5] => 41.4
        [key6] => 46.58
        [key7] => 48.8
        [key8] => 52.69
        [key9] => 48.9
    )

[2] => Array
    (
        [key1] => 20.23
        [key2] => 26.9
        [key3] => 32.39
        [key4] => 36.95
        [key5] => 41.48
        [key6] => 46.41
        [key7] => 48.82
        [key8] => 52.58
        [key9] => 49.42
    )

)

但这会导致类似的情况

$indice = array();
$aux = array();
foreach ($arrData as $key => $value) {
  foreach ($value as $k => $v) {
    $indice[$key][$k] = array_push($aux, $v);
  }
}

我希望实现一个索引数组,该数组保留与原始数组相同的结构

Array
(
    [0] => Array
        (
            [key1] => 1
            [key2] => 2
            [key3] => 3
            [key4] => 4
            [key5] => 5
            [key6] => 6
            [key7] => 7
            [key8] => 8
            [key9] => 9
        )

    [1] => Array
        (
            [key1] => 10
            [key2] => 11
            [key3] => 12
            [key4] => 13
            [key5] => 14
            [key6] => 15
            [key7] => 16
            [key8] => 17
            [key9] => 18
        )

    [2] => Array
        (
            [key1] => 19
            [key2] => 20
            [key3] => 21
            [key4] => 22
            [key5] => 23
            [key6] => 24
            [key7] => 25
            [key8] => 26
            [key9] => 27
        )

)

是否可以使关联数组成为索引数组?

感谢您的回复!

1 个答案:

答案 0 :(得分:1)

<?php
$a[0]['key1']=1;
$a[0]['key2']=2;
$a[1]['key1']=3;
$a[1]['key2']=4;

foreach ($a as $b){
    $new[] = array_values($b);
}

print_r($new);

输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

)

ref:https://www.php.net/manual/en/function.array-values.php