How to show these massives by two pair? - php

I need to sort these massives:
$arr1 = array(
'audio',
'audio',
'audio',
'audio',
'audio',
);
$arr2 = array(
'video',
'video',
'video'
);
Using a for loop:
$result = array_merge($arr1, $arr2);
for($i = 0; $i < count($result); $i++){
$finally_arr[] = $arr1[$i];
$finally_arr[] = $arr2[$i];
}
Finally I want to get like this:
$finally_arr = array(
[0] => audio
[1] => video
[2] => video
[3] => audio
[4] => audio
[5] => video
[6] => audio
[7] => audio
);
The first item is single, others come in pairs, like chess:
audio video
video audio
audio video
audio audio
Providing that items in array which is more, go down together.
How to write this loop?

$lenght = max(count($arr1), count($arr2));
$i = 0;
while ($i < $lenght){
// One order
if(array_key_exists($i, $arr1))
$finally_arr[] = $arr1[$i] . '<br>';
if(array_key_exists($i, $arr2))
$finally_arr[] = $arr2[$i] . '<br>';
if(++$i >= $lenght) break;
// Revert order
if(array_key_exists($i, $arr2))
$finally_arr[] = $arr2[$i] . '<br>';
if(array_key_exists($i, $arr1))
$finally_arr[] = $arr1[$i] . '<br>';
$i++;
}

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 lists of arrays

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

Sum and Average in multi-dimentional arrays with php

I'm trying to get sum and average of visitors from the following multi-dimensional array :
Array([visitors] => Array(
[2015-06-12] => Array([0] => Array([value] => 29))
[2015-06-11] => Array([0] => Array([value] => 55))
...
))
I cannot manage to find a way to get the results i need as i get lost with "foreach".
Can anybody help please ?
Use this
<?php
$mainarray = array('visitors' => Array(
'2015-06-12' => Array(Array('value' => 29)),
'2015-06-11' => Array(Array('value' => 55))));
$sum = 0;
$count = 0;
$visitor = $mainarray['visitors'];
foreach ($visitor as $key => $val) {
$sum += $val[0]['value'];
$count++;
}
echo "Sum is " . $sum."<br>";
$average = ($sum / $count);
echo "Average is " .$average."<br>";;
?>

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

Imploding with "and" in the end?

I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>

Categories