PHP dynamic lists of arrays - php

Please can somebody help me with a solution to make a a string list of array like:
$string=array1, array2, .........., arrayn.
I need to generate this list dynamically.
Now I send it each array in list but I want to increase the numbers and I wonder how to put arrays dynamically inside the list.
In my code I have something like this:
$array[$j]
I need to create a list like this:
$string=$string.','.$array[$j]
...but it doesn't work. I can't send it as a multidimensional array.
Does anyone have any ideas?

if you are talking about a multidimensional array:
$container[0] = $string;
$container[1] = $array;
$container[2] = $my_other_array;
// ...
then for example $container[1] will contain your $array and with $container[1][$j] you can access the key $j in your original array.

My code is
$Copii = [];
$Config_Camere = [];
$nrCamere = $array['Camere'];
for ($i = 1; $i <= $nrCamere; $i++) {
if ($array['Copii_Cam' . $i] >= 1) {
for ($j = 1; $j <= $array['Copii_Cam' . $i]; $j++) {
$Copii[$j] = array_combine(['AgeQualifyingCode', 'Count', 'Age'], ['c', '1', $array['varstaCopil' . $j . '_Cam' . $i]]);
}
if ($array['Copii_Cam' . $i] == 2) {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => [['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]], $Copii[1], $Copii[2]]]];
} else if ($array['Copii_Cam' . $i] == 1) {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => [['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]], $Copii[1]]]];
}
} else {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => ['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]]]];
}
}
And if you see i want to generate dinamicaly the array $Copii
Thanks a lot

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 - add values to already existing array

I have a already defined array, containing values just like the one below:
$arr = ['a','b','c'];
How could one add the following using PHP?
$arr = [
'a' => 10,
'b' => 5,
'c' => 21
]
I have tried:
$arr['a'] = 10 but it throws the error: Undefined index: a
I am surely that I do a stupid mistake.. could someone open my eyes?
Full code below:
$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
if ($stage->finish_type) {
if(!in_array($stage->finish_type, $finishes)){
array_push($finishes, $stage->finish_type);
}
}
}
foreach ($projectunits as $unit) {
$data[$i] = [
'id' => $unit->id,
'project_name' => $unit->project_name,
'block_title' => $unit->block_title,
'unit' => $unit->unit,
'core' => $unit->core,
'floor' => $unit->floor,
'unit_type' => $unit->unit_type,
'tenure_type' => $unit->tenure_type,
'floors' => $unit->unit_floors,
'weelchair' => $unit->weelchair,
'dual_aspect' => $unit->dual_aspect
];
$st = array();
$bs = '';
foreach ($projectstages as $stage) {
$projectmeasure = ProjectMeasure::select('measure')
->where('project_id',$this->projectId)
->where('build_stage_id', $stage->id)
->where('unit_id', $unit->id)
->where('block_id', $unit->block_id)
->where('build_stage_type_id', $stage->build_stage_type_id)
->first();
$st += [
'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
];
if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
$height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
$st += [
'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
];
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
}
} else {
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
}
}
}
$data[$i] = array_merge($data[$i], $st);
$data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
$i++;
}
The above code is used as is and the array $finishes is the one from the first example, called $arr
You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign a new index with that value if it doesn't exist.
+= can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value.
If you want to convert the array of strings to a collection of keys (elements) and values (integers), you can try the following:
$arr = ['a','b','c'];
$newVals = [10, 5, 21];
function convertArr($arr, $newVals){
if(count($arr) == count($newVals)){
$len = count($arr);
for($i = 0; $i < $len; $i++){
$temp = $arr[$i];
$arr[$temp] = $newVals[$i];
unset($arr[$i]);
}
}
return $arr;
}
print_r(convertArr($arr, $newVals));
Output:
Array ( [a] => 10 [b] => 5 [c] => 21 )

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));

Sorting arrays by value

I have this post array
Array (
[imgurl_3] => http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg
[imgtekst_3] => Write a text for the slide
[imgurl_4] => http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg
[imgtekst_4] => Write a text for the slide
[update_gallery] => Save changes )
The numbers in the end of the imgurl and imgtekst are dynamic. So.
I want to pair the imgurl_3 & imgtekst_3, and so on. To update into a database.
Any smart PHP functions for this?
Thanks
$array = [
'imgurl_3' => 'http://localhost/wordpress/wp-content/uploads/2014/03/05-239x300.jpg',
'imgtekst_3' => 'Write a text for the slide',
'imgurl_4' => 'http://localhost/wordpress/wp-content/uploads/2014/03/img_2184-300x225.jpg',
'imgtekst_4' => 'Write a text for the slide',
'update_gallery' => 'Save changes'
];
$output = [];
foreach ($array as $key => $item) {
$intKey = filter_var($key, FILTER_SANITIZE_NUMBER_INT);
if ($intKey) {
$key = preg_replace('/_\d/', '', $key);
$output[$intKey][$key] = $item;
}
}
print_r($output);
You could use a for loop and select correlated entries:
for($i = 0; $i < $whatever; $i++) {
if(array_key_exists('imgurl_' . $i, $array)) {
$value = $array['imgurl_' . $i];
$value2 = $array['imgtekst_' . $i];
}
$sqlQuery = '<UPDATE using $value and $value2>';
}

Find maximum value in associative array

I have a associative array:
$users[0] = array('name' => 'Jim', 'depth' => '1', 'bk_id' => '9');
$users[1] = array('name' => 'Jill', 'depth' => '3', 'bk_id' => '10');
$users[2] = array('name' => 'Jack', 'depth' => '7', 'bk_id' => '17');
I would like to know a way of finding the array index with the maximum or greatest depth value?
Any suggestion is most appreciated.
Just iterate and look at the maximum value:
var max = 0, maxIndex = -1;
for(var i=0;i<users.length;i++) {
if(parseInt(users[i].depth,10) > max) {
max = users[i].depth;
maxIndex = i;
}
}
console.log("Your maximum depth is %d at index %d", max, maxIndex);
From PHP:
$index = 0;
$max = 0;
for ($i = 0; $i < count($users); $i++) {
if ($users[$i]['depth'] > $max) {
$max = $users[$i]['depth'];
$index = $i;
}
}
echo $users[$index]['name'] . ' has the greatest depth.';
Since the question is unclear, here's how to find it with PHP.
foreach ($users as $index => $user) {
if (!isset($maxdepth)) {
$maxdepth = $user['depth'];
$maxindex = $index;
}
else {
if ($user['depth']) > $maxdepth) {
$maxindex = $index;
$maxdepth = $user['depth'];
}
}
echo "Index: $maxindex";
You can either iterate over all the key-value pairs looking at the depth value each time, or sort the $users array using a custom sort function like sort_func(){ return a.depth - b.depth}
Using native sort function?
function getDeepestItem(arr)
{
arr.sort(function(a,b){return a['depth'] < b['depth'];});
return arr[0]
}

Categories