mafortis
mafortis

Reputation: 7128

push multiple values to array

I have array of data like:

array:2 [
  0 => array:1 [
    "image" => "attachment-T48Pi7oAov.jpg"
  ]
  1 => array:1 [
    "image" => "attachment-IF8VG2pypn.jpg"
  ]
]

I need to push 2 more values into each of this arrays like:

array:2 [
  0 => array:1 [
    "image" => "attachment-T48Pi7oAov.jpg",
    "attachable_type" => "whatever",
    "attachable_id" => "whatever"
  ]
  1 => array:1 [
    "image" => "attachment-IF8VG2pypn.jpg",
    "attachable_type" => "whatever",
    "attachable_id" => "whatever"
  ]
]

If i use array_push or array_unshift it returns numbers such as 6 or 3

Code

if ($image = $request->file('attachments')) {
    foreach ($image as $files) {
        $filePath = public_path('images/attachment/');
        $filename = 'attachment' . '-' . str_random(10) . '.' . $files->getClientOriginalExtension();
        $files->move($filePath, $filename);
        $names[]['image'] = "$filename";
        $type['attachable_type'] = "App\ProjectScheduleVisit";
        $id['attachable_id'] = "$visit->id";

        $insert = array_push($names, $type, $id);
    }
}

Any ideas?

Upvotes: 1

Views: 442

Answers (3)

unclexo
unclexo

Reputation: 3941

Just an example for you

$a = [
  [
    "image" => "attachment-T48Pi7oAov.jpg",
  ],
  [
    "image" => "attachment-IF8VG2pypn.jpg",
  ],
];

foreach ($a as $key => $value) {
    $a[$key]['attachable_type'] = rand(1, 100);
    $a[$key]['attachable_id'] = rand(1, 100);
}

print_r($a);

Upvotes: 1

bishop
bishop

Reputation: 39354

In your loop, package all the values as an array and push it at once:

$package = [
    'image' => $filename,
    'attachable_type' => App\ProjectScheduleVisit::class,
    'attachable_id' => $visit->id,
]
$names[] = $package;

If you also need attachable type and id in separate arrays (as suggested by your code, but that may be an artifact of your attempts), then pull them out of package:

$type['attachable_type'] = $package['attachable_type'];
$id['attachable_id'] = $package['attachable_id'];

Upvotes: 1

Ahmed Shefeer
Ahmed Shefeer

Reputation: 395

Try iterating over the array and pushing the required element to each of the subarrays.

array_walk(
        $array,
        function (&$item, $key) {
            $item['attachable_type'] = 'whatever';
            $item['attachable_id'] = 'whatever';
        }
    );

Upvotes: 0

Related Questions