John Davidson

breaking down an array of two arrays from input PHP

0 comments
Message:


I posted array below with postman to my PHP API and it is stored perfectly and I can print_r and see it:


$sizes = [['new_width' => 100, 'new_height' => 300], ['new_width' => 400, 'new_height' => 200]];

how I stored the sizes


$sizes = $_POST['sizes'];

postman result from print_r($sizes):


<pre>Array
(
[0] => Array
(
['new_width'] => 100
['new_height'] => 300
)

[1] => Array
(
['new_width'] => 400
['new_height'] => 200
)

)

but when I want to see each array of size separately, I fail.


        foreach ($sizes as $size) {
$size = [$_POST['new_width'], $_POST['new_height']];
echo '<pre>';
print_r($size);
die();
}

this is what postman returns as result:


<pre>Array
(
[0] =>
[1] =>
)

so it obviously can't store new_width and new_height for size.
how can I do it the right way?



My Answer:
> To break down an array of two arrays in PHP, you can access the elements of the inner arrays using nested loops or by directly accessing the elements using their indexes.

Here is an example of how you can access the elements of the `$sizes` array:

php
$sizes = [['new_width' => 100, 'new_height' => 200], ['new_width' => 150, 'new_height' => 250]];

// Accessing elements using nested loops
foreach ($sizes as $size) {
foreach ($size as $key => $value) {
echo $key . ': ' . $value . "\n";
}
}

// Accessing elements directly
echo $sizes[0]['new_width']; // Output: 100
echo $sizes[0]['new_height']; // Output: 200
echo $sizes[1]['new_width']; // Output: 150
echo $sizes[1]['new_height']; // Output: 250


You can use this approach to access and manipulate the elements of the inner arrays within the `$sizes` array.

Rate this post

3 of 5 based on 8750 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us