My code
$str = array(fgets($da, 1024));
print_r($str);
I'm trying to create an array in php from a dynamic output , but i noticed the keys in all object are [0], i need to assign a diferent key number to each object, how can i do that ?
Looks weird to me that all keys are 0, im trying to figure but nothing helps me.
Result :
Array
(
[0] =>
)
Array
(
[0] => 200
)
Array
(
[0] => 819105 rs fs
)
Array
(
[0] => 300 tert
)
Array
(
[0] => THO
)
Array
(
[0] => 91362
)
Array
(
[0] =>
)
Array
(
[0] => 06-20-21 6:56 PM
)
Array
(
[0] =>
)
Array
(
[0] =>
Array
(
[0] => 3 Cat 20 4.82 0.0 7.4 30
)
Array
(
[0] => 4 Dogs 19 26.2 0.8 7.1 62
)
Array
(
[0] =>
)
Thanks
My Answer:
To assign different key numbers to each object in the array, you can use a loop to iterate over the objects and assign keys incrementally. Here's an example of how you can achieve this:
php
$str = array(fgets($da, 1024));
$newArray = array();
$key = 0;
foreach ($str as $value) {
$newArray[$key++] = $value;
}
print_r($newArray);
In this code snippet, we create a new empty array `$newArray` and initialize a key variable `$key` to 0. We then loop through the original array `$str`, assigning each value to the new array with the current key value and then incrementing the key. This way, each object in the array will have a different key number starting from 0 and incrementing by 1 for each object.
Rate this post
3 of 5 based on 1516 votesComments