How to Create a Nested Array Out of an Array in PHP

How to create a nested array out of an array in PHP

$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
$temp = array($array[$i] => $temp);
}

How to create nested arrays in PHP?

Use:

    <?php
$myarr=[
"name"=>"sami",
"family"=>"soheili",
"details" => [
"telephone" => "072...",
"email" => "test@yahoo.com"
]
];

Create nested array by array of keys

you don't need recursion, just do it from the right to left:

$a = $value;
for ($i = count($keys)-1; $i>=0; $i--) {
$a = array($keys[$i] => $a);
}

or the even shorter version from @felipsmartins:

$a = $value;
foreach (array_reverse($keys) as $valueAsKey) $a = [$valueAsKey => $a];

Create array from nested array with php

More simplified @NigelRen's solution is using array_column:

$output = array_column($users, 'value', 'title');

How to delete a nested array inside of an array

Use unset()

if(isset($array['termin'])){
unset ($array['termin']);
}

Output:- https://3v4l.org/1Yj4F

Note:- isset() used to check that index exist or not, if not function call will saved.

Change the structure of the array (make nested arrays in the array)

Make an iteration over the array using array_walk(). In every cycle of the iteration check weather the key already exist in the $res array. If exist then create array merging with old value and assign to the same key. If not key already exist then assign the $val to the $res array.

$data = array("1536" => "12","1695" => "Korea","1904" => "10/7","1905" => "", "1906" => null,"1907" => "1.1","1906.1" => "H1","1906.2" => "H35","1905.1" => "15");

$res = array();
array_walk($data, function($val, $key) use(&$res) {
$key = intval($key);
if (array_key_exists($key, $res)) {
$res[$key] = is_array($res[$key]) ? array_merge($res[$key], [$val]) : array_merge([$res[$key]], [$val]);
} else {
$res[$key] = $val;
}
});

print_r($res);

Working demo.

How to create nested array ancestors recursively in PHP

You could first make use of array_column to group your entries by ID, then array_reduce to build your new array that includes ancestors (without altering the base one):

$entriesById = array_column($array, null, 'id');

$entriesWithAncestors = array_reduce(
$entriesById,

static function (array $result, array $entry) use ($entriesById): array {
$result[$entry['id']] = $entry + ['ancestors' => []];
$parentId = $entry['parentId'];
while (isset($result[$parentId])) {
$result[$entry['id']]['ancestors'][] = $result[$parentId];
$parentId = $entriesById[$parentId]['parentId'] ?? null;
}
return $result;
},

[]
);

print_r($entriesWithAncestors);

Demo

Note that this assumes parent entries are always present before their children in the original array, as you mentioned in the comments.

How to create multidimensional array in nested loop while?

There is no hurry to create the array, wait till you have everything, so create the new array at the end of the outer loop, and build a temp array for the productContent array, put it all together at then end

if (have_rows('dodaj_pytania_do_produktu')):

while (have_rows('dodaj_pytania_do_produktu')) : the_row();

$productID = get_sub_field('nazwa_produktu_faq');
$productImage = get_sub_field('dodaj_zdjecie');

$product = wc_get_product($productID);
$productName = $product->get_title();
// Loop over sub repeater rows.
if (have_rows('dodaj_pytanie_i_odpowiedz')):
$x = 1; // counter
$pc = [];
while (have_rows('dodaj_pytanie_i_odpowiedz')) :
the_row();
$question = get_sub_field('dodaj_pytanie');
$answer = strip_tags(get_sub_field('dodaj_odpowiedz'));

// build the inner loop content here
$pc[] = ["question$x" => $question,
"answer$x" => $answer
];
$x++;
endwhile;

// put it all together here
$productsData[] = [
'productId' => $productID,
'productImg' => $productImage,
'productContent = $pc
];

endif;
endwhile;
else :
echo "brak faq";
endif;

Multiple nested array from MySQL query in PHP

There's plenty of room for improvement in this code but I've ignored that and tried to keep the code matching yours in this example.

The main changes are:

  • Create a temporary variable $user_plant_array which we store "plant_images" against
  • Push that temporary variable to the $site_array at the end of the loop
  • Rename some loop variables to making it easier to identify what you're referencing
$json_response = array();
$sites = array();
if ($result->num_rows > 0) {

while ($site = $result->fetch_object()) {
$sites[] = $site;
}

foreach ($sites as $site) {
$site_array = (array)$site;
$site_id = $site->site_id;

$user_plants = "SELECT A.user_plant_id, A.site_id, A.plant_id FROM user_plants A RIGHT JOIN sites B ON A.site_id ='" . $site_id . "'
JOIN plants C ON A.plant_id = C.plant_id GROUP BY A.user_plant_id";
$resultSet = $this->conn->query($user_plants);

$user_plants = array();
if ($resultSet->num_rows > 0) {

while ($user_plant = $resultSet->fetch_object())
$user_plants[] = $user_plant;

foreach ($user_plants as $user_plant) {
// create a temporary variable here that we will map
// all "plant_images" to
$user_plant_array = (array)$user_plant;

$plant_id = $user_plant->plant_id;
$user_plant_id = $user_plant->user_plant_id;

$plant_images = "SELECT A.plant_image_id FROM plants_images A WHERE A.plant_id ='" . $plant_id . "' UNION SELECT B.plant_image_id FROM user_plant_image B JOIN user_plants C ON B.user_plant_id ='" . $user_plant_id . "' WHERE C.user_id ='" . $user_id . "' GROUP BY B.plant_image_id ORDER BY plant_image_id";
$resultSet = $this->conn->query($plant_images);

$plant_images = array();
if ($resultSet->num_rows > 0) {

while ($plant_image = $resultSet->fetch_object())
$plant_images[] = $plant_image;

foreach ($plant_images as $plant_image) {
$user_plant_array['plant_images'][] = $plant_image;
}

} else if ($resultSet->num_rows == 0) {
$user_plant_array['plant_images'] = [];
}

// the temporary variable now contains all "plant_images"
// now we can push that to the site array
$site_array['user_plants'][] = $user_plant_array;
}

$json_response[] = $site_array;
}
}
}

return $json_response;


Related Topics



Leave a reply



Submit