How to loop inside an array inside a loop in PHP - php

Basically, what I'm trying to do is loop inside a loop and in arrays. I have no idea how to do it (that's why I'm here) and I've been testing many things.
As it sounds very confused I write down the code how it would be, but clearly that's not correct.
This below is what I've tried.
$whatever->insertOne(
['name' => 'whatever',
'data' => array(
for ($i = 0 ; $i < 50 ; $i++) { // <-first loop
'something' => array(
for ($j = 0 ; $j < 50 ; $j++) { // <-second loop
'somevalue' => array(
'date' => $date,
'value' => mt_rand(0,200)
)
}
)
}
)
]);

Try this out:
$data = array();
for ($j = 0 ; $j < 50 ; $j++) {
for ($i = 0 ; $i < 50 ; $i++) {
$data[$j]['something'][$i]['date'] => $date;
$data[$j]['something'][$i]['value'] => mt_rand(0,200);
}
}
$whatever->insertOne(['name' => 'whatever','data' => $data]);

Loop need to be outside to create final array. Don't add loop inside an array.
You probably need something like below:-
$data = ['name' => 'whatever'];
for ($i = 0 ; $i < 50 ; $i++) {
for ($j = 0 ; $j < 50 ; $j++) {
$data[$i]['something'][$j]=['somevalue' => array('date' => $date,'value' => mt_rand(0,200));
}
}
$whatever->insertOne($data);
Note:- you can print your array before insertOne() to check that you are getting array of correct format or some more manipulation needed.Thanks

Related

How to merge 3 arrays keeping their meta key?

I'm Getting some arrays from some wordpress custom fields:
$content = array(get_post_meta($postId, 'content'));
$media = array(get_post_meta($postId, 'media'));
$yt = array(get_post_meta($postId, 'youtube'));
I then need to have it printing in sequence, like:
media
content
LInk
Embed
And repeat the sequence for each value
media
content
LInk
Embed
For the sequence I'd use this:
echo '<ul>';
for ($i = 0; $i < count($all_array['media']); $i++) {
for ($j = 0; $j < count($all_array['content']); $j++) {
for ($k = 0; $k < count($all_array['youtube']); $k++) {
echo '<li>media->' . $all_array['media'][$i] . '</li>';
echo '<li>content->' . $all_array['content'][$j] . '</li>';
echo '<li>link->' . $all_array['link'][$k] . '</li>';
}
}
}
echo '</ul>';
But I'm doing something wrong with the merging of the 3 fields as if I do a var_dump before to run the for bit, like
echo '<pre>' . var_export($all_array, true) . '</pre>';
Then this is what I get and I cannot iterate as I wish:
array (
0 =>
array (
0 =>
array (
0 => '
brother
',
1 => '
Lorem
',
2 => '
End it
',
),
1 =>
array (
0 => '337',
1 => '339',
),
2 =>
array (
0 => 'https://www.youtube.com/watch?v=94q6fzbJUfg',
),
),
)
Literally the layout in html that I'm looking for is:
image
content
link
image
content
link
...
UPDATE
This how I am merging the arrays:
foreach ( $content as $idx => $val ) {
$all_array[] = [ $val, $media[$idx], $yt[$idx] ];
}
This is the associative array how it looks like:
Content:
array (
0 =>
array (
0 => '
brother
',
1 => '
Lorem
',
2 => '
End it
',
),
)
Media
array (
0 =>
array (
0 => '337',
1 => '339',
),
)
Youtube
array (
0 =>
array (
0 => 'https://www.youtube.com/watch?v=94q6fzbJUfg',
),
)
The way I've resolved it is first I calculate the tot. items within each array, then I get the array with max items and loop and add the items in sequence:
//GET CUSTOM FIELDS
$content = get_post_meta($post_to_edit->ID, 'content', false);
$media = get_post_meta($post_to_edit->ID, 'media', false);
$yt = get_post_meta($post_to_edit->ID, 'youtube', false);
$max = max(count($content), count($media), count($yt));
$combined = [];
//
// CREATE CUSTOM FIELDS UNIQUE ARRAY
for($i = 0; $i <= $max; $i++) {
if(isset($media[$i])) {
$combined[] = ["type" => "media", "value" => $media[$i]];
}
if(isset($content[$i])) {
$combined[] = ["type" => "content", "value" => $content[$i]];
}
if(isset($yt[$i])) {
$combined[] = ["type" => "youtube", "value" => $yt[$i]];
}
}
Finally I can loop:
foreach ($combined as $key => $val) {
if($val['type'] === "media") {
...
}
if($val['type'] === "content") {
...
You don't need to merge the arrays together. It will work fine in separate arrays. However, your for loops don't have the right logic. Try:
for ($i = 0; $i < count($media); $i++) {
for ($j = 0; $j < count($media[$i]); $j++) {
echo '<li>media->' . $media[$i][$j] . '</li>';
}
for ($j = 0; $j < count($content[$i]); $j++) {
echo '<li>content->' . $content[$i][$j] . '</li>';
}
for ($j = 0; $j < count($youtube[$i]); $j++) {
echo '<li>link->' . $youtube[$i][$j] . '</li>';
}
}

PHP dynamic variable

I'm working in PHP.
I have a dynamic number of arrays called 'placeholder0, placeholder1, placeholder2....' and I want to json_encode them
$encode = json_encode(array('tabs' => $tabs, 'placeholder0' => $placeholder0, 'placeholder1' => $placeholder1, 'placeholder2' => $placeholder2 ..... ));
The number of values inside the 'tabs' array is the same as the number of 'placeholder' arrays.
How can I do this?
$result = array('tabs' => $tabs);
for ($i = 0; $i < count($tabs); $i++) {
$result['placeholder' . $i] = ${'placeholder' . $i};
}
file_put_contents($jsonLocation, json_encode($result));

JSON encoding from wordpress database values

I need a proper JSON file with "geo_langitude", "geo_latitude", "adress" & "url" values
I have wp database with post_meta "property" - "geo_langitude" "geo_latitude" & "address" in there.
my file is smth like that
<?php
function return_markers($count) {
$query = new WP_Query('post_type=property&posts_per_page=-1&orderby=menu_order&order=DESC&post_status=publish');
$array = array();
$i = 0;
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => get_post_meta($post->ID,'geo_latitude',true),
'y' => get_post_meta($post->ID,'geo_longitude',true),
'z' => $i
);
$array[] = $elem;
}
echo json_encode($elem);
};
return_markers($i);
?>
It's my first time using JSON so I have troubles and I don't know where. =(
with random markers work perfectly:
<?php
function return_markers($count) {
$array = array ();
for ($i = 0; $i< $count; $i++) {
$elem = array(
't' => 'string '.$i,
'x' => 23 + (rand ( 0 , 10000 ) / 10000) * 5,
'y' => 56.2 + (rand ( 0 , 10000 ) / 10000) * 0.8,
'url' => '#map_redirect_'.$i,
'z' => $i
);
$array[] = $elem;
}
echo json_encode($array);
};
return_markers(23);
?>

Creating two dimentional array in for-loop

I want to create an array in a for-loop so i can adjust the size ($i) of the array.
I've tried this:
$array = array();
for($i = 1; $i <= 5; $i++) {
array_push($array,
$i => array(
"id" => "",
"option" => ""
)
);
}
But I get the following error:
Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in ...
I'v also tried to make it a string by doing $i."" on line 4 but that doesn't seem to work either. Does anyone know why?
More idiomatic would be:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => "") ;
}
However note that this will give you array indexes from 1-5. Arrays are usually indexed from 0:
$array = array();
for($i = 0; $i < 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => "") ;
}
But this can be done without specifying the key:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[] = array(
"id" => "",
"option" => "") ;
}
try this:
$array = array();
for($i = 1; $i <= 5; $i++) {
$array[$i] = array(
"id" => "",
"option" => ""
);
}
Remove the $i =>
$array = array();
for($i = 1; $i <= 5; $i++) {
array_push($array, array(
"id" => "",
"option" => ""
)
);
}

Overlapping Associative Arrays

I need to overlap data from multiple associative arrays with the following considerations:
If a matching key exists, overwrite it
If a key exists but doesn't match, append new value to that element
If neither of the above, create an element to store the value
Take for example the following structures:
<?php
for ($i = 0; $i < 10; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 12,
'column' => 5
)
);
}
for ($i = 4; $i < 12; $i++) {
$table["table_$i"] = array(
"cell_0" => array(
'row' => 9,
'column' => 8
)
);
}
for ($i = 5; $i < 15; $i++) {
$table["table_$i"] = array(
"cell_1" => array(
'row' => 4,
'column' => 1
)
);
}
?>
The desired output would look like this:
{"table_0":{"cell_0":{"row":12,"column":5}},"table_1":{"cell_0":{"row":12,"column":5}},"table_2":{"cell_0":{"row":12,"column":5}},"table_3":{"cell_0":{"row":12,"column":5}},"table_4":{"cell_0":{"row":9,"column":8}},"table_5":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_6":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_7":{"cell_1":{"row":4,"column":1}},"table_8":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_9":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_10":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_11":{"cell_0":{"row":9,"column":8},"cell_1":{"row":4,"column":1}},"table_12":{"cell_1":{"row":4,"column":1}},"table_13":{"cell_1":{"row":4,"column":1}},"table_14":{"cell_1":{"row":4,"column":1}}}
Take note from the desired output that the value of cell_0 doesn't replace the value of cell_1: I couldn't get the desired output using array_merge() in this case.
Any help would be appreciated--thanks!
Check array_merge and array_unique php functions.

Categories