code-8
code-8

Reputation: 58632

How can I construct an array with a specific key using PHP?

I have an array of 4 elements $device_report = []; with these data in it

array:4 [▼
  0 => array:2 [▼
    "up_bytes" => 2818
    "down_bytes" => 948
  ]
  1 => array:2 [▼
    "up_bytes" => 472
    "down_bytes" => 439
  ]
  2 => array:2 [▼
    "up_bytes" => 3364
    "down_bytes" => 1317
  ]
  3 => array:2 [▼
    "up_bytes" => 3102
    "down_bytes" => 1682
  ]
]

Right now, I have this

    $device_report = [];
    foreach ($devices as $device){
        $device_mac = $device->device_mac; //080027E2FC7D
        $data = VSE::device($device_mac);
        array_push($device_report,$data);
    }

I've tried

    $device_report = [];
    foreach ($devices as $device){
        $device_mac = $device->device_mac; //080027E2FC7D
        $data = VSE::device($device_mac);
        array_push($device_report[$device_mac],$data);
    }

It give me error :

array_push() expects parameter 1 to be array, null given


I just want to my key to be a specific device Mac Address rather than 0,1,2,3.

Any hints will be much appreciated !

Upvotes: 1

Views: 75

Answers (3)

Oberst
Oberst

Reputation: 477

I wouldnt use array_push for this. No reason to.

$device_report = [];
foreach ($devices as $device){
    $device_mac = $device->device_mac; //080027E2FC7D
    $data = VSE::device($device_mac);
    $device_report[$device_mac]=$data; // <-- This line changed
}

Upvotes: 1

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

Try the following:

$device_report = [];
foreach ($devices as $device){
    $device_mac = $device->device_mac; //080027E2FC7D
    $data = VSE::device($device_mac);

    //add this to init the array.
    if (is_array($device_report[$device_mac]) === false) {
        $device_report[$device_mac] = [];
    }

    array_push($device_report[$device_mac],$data);
}

The error message appear because $device_report[$device_mac] is null. You have to initialize the value with an array. With the following code you initialize it with a empty array if no array is available:

//add this to init the array.
if (is_array($device_report[$device_mac]) === false) {
    $device_report[$device_mac] = [];
}

Upvotes: 1

War10ck
War10ck

Reputation: 12508

Per the documentation, array_push:

int array_push ( array &$array , mixed $value1 [, mixed $... ] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

In your particular case, you're trying to create a new key and assign the array, so you're getting the error that $device_report[$device_mac] is not an array. This is indeed correct since the key doesn't already exist.

To overcome this, assign the array directly as oppose to using array_push.

Try this:

$device_report[$device_mac] = $data;

instead of:

array_push($device_report[$device_mac], $data);

Upvotes: 2

Related Questions