0

I have this array:

array:2 [▼
  0 => array:3 [▼
    "time" => 7780
    "name" => "John A. Doe"
    "photo" => "johndoe.png"
  ]
  1 => array:3 [▼
    "time" => 49800
    "name" => "Jane B. Doe"
    "photo" => "janedoe.png"
  ]
]

the time value is seconds, my question is how can i loop through the array so that I can run a function like:

"time" => $this->secondsToHumanReadable(49800)

My function secondsToHumanReadable is tested and working fine, i just want it to insert on the time value inside my array result.

UPDATE:

Desired output will be:

array:2 [▼
      0 => array:3 [▼
        "time" => '2 days, 1 hour, 3 minutes, 45 seconds'
        "name" => "John A. Doe"
        "photo" => "johndoe.png"
      ]
      1 => array:3 [▼
        "time" => '3 hour, 15 minutes, 20 seconds'
        "name" => "Jane B. Doe"
        "photo" => "janedoe.png"
      ]
    ]
kapitan
  • 2,008
  • 3
  • 20
  • 26
  • 5
    With a `foreach`, no? – u_mulder Mar 27 '19 at 13:14
  • Possible duplicate of [How to get an array of specific "key" in multidimensional array without looping](https://stackoverflow.com/questions/7994497/how-to-get-an-array-of-specific-key-in-multidimensional-array-without-looping) – Martijn Mar 27 '19 at 13:16
  • @Martijn, I don't think that is a duplicate because the OP wants a loop. – reisdev Mar 27 '19 at 13:16
  • 1
    @kapitan Do you want to modify the original array, or produce a new one? – programmer-man Mar 27 '19 at 13:22
  • @programmer-man - thank you for asking, my question was updated. my answer to your question is either, i just want the easiest solution for this. anyways, someone already gave the answer below. thank you for your time. – kapitan Mar 27 '19 at 13:29

4 Answers4

5

Using array_map()

$new_array = array_map(function($item) use ($this) {
  $item['time'] = $this->secondsToHumanReadable($item['time']);
  return $item;
}, $my_array);

Benefit of using array_map() is that the returned array is a new array, so you don't mutate your initial array. It's usually a good practice not to mutate data structures

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
0

You could use a foreach, as @u_mulder said.


// Copying the original array
$result = $array;

foreach($result as $item) {
    $item["time"] = $this->secondsToHumanReadable($item["time"]);
}

print_r($result);
reisdev
  • 3,215
  • 2
  • 17
  • 38
0

You could use a foreach but with references:

$data = [
  [
    'time' => time()
  ],

  [
    'time' => time() - 5000
  ]
];

foreach ($data as &$datum) {  
  $datum['time'] = date('d/m/Y', $datum['time']);
}

print_r($data);

Output

Array
(
    [0] => Array
        (
            [time] => 27/03/2019
        )

    [1] => Array
        (
            [time] => 27/03/2019
        )

)

Live Example

Repl

Script47
  • 14,230
  • 4
  • 45
  • 66
0

You can try this

array(
  "time" => function($foo){return $foo;},
    "name" => "John A. Doe",
    "photo" => "johndoe.png"
);
sc0rp1on
  • 348
  • 1
  • 15