I have an array like this:
$survey = array(
'Category1' => array(
'Question1' => array(
'Option1', 'Option2', 'Option3'
),
'Question2' => array(
'Option1', 'Option2', 'Option3'
)
),
'Category2' => array(
'Question1' => array(
'Option1', 'Option2', 'Option3'
),
'Question2' => array(
'Option1', 'Option2', 'Option3'
)
)
);
This array is in practice much larger. The requirement is 3 questions per page. My thought was to store which category and question I'm currently on. For example category 0, question 2. Then check to see if array_key_exists and if so, display, if not, increment and try again. As you might have guessed, categories and questions don't have keys (at least not numeric ones for me to loop through). So using an index is, as far as I know, is out of the question. How can I dynamically display 3 questions per page and automatically get the next 3 questions for the next page without knowing what the value is for category2, for example. How can I traverse/target this?
Thanks,
Ryan
The data seems fairly static so i would suggest changing the data format :)
Change the array into something like:
$survey = array(
array( 'name' = > 'Category1',
'questions' => array(
array(
'name' => 'Question1',
'opts' => array(
'Option1', 'Option2', 'Option3'
)
),
array(
'name' => 'Question2',
'opts' => array(
'Option1', 'Option2', 'Option3'
)
)
),
array( 'name' = > 'Category2',
'questions' => array(
array(
'name' => 'Question1',
'opts' => array(
'Option1', 'Option2', 'Option3'
)
),
array(
'name' => 'Question2',
'opts' => array(
'Option1', 'Option2', 'Option3'
)
)
)
);
And you can use integer indexes then. Just remember 2 number (the category index and the question index inside the category. And just increment until end of array in each case.
Php is not my strongest language so the code above might look strange to a native php programmer. However the root cause of OP's difficulties is the inability to easily create an interator type object. This is because of the fact that the key based array have a "strange" order given by their hash map nature. Change the nature and allow yourself to build an interator like object (aka an array index).
Since you're using an associative array (aka hash), there is no order to it. Each question and each category need to have the next question/category key with them. After that, see link-list algorithms.
My be array_keys() function will help you? You will iterate keys array (to get next keys).
<?php
$survey = array(
'Category1' => array(
'Question1' => array(
'Option1', 'Option2', 'Option3'
),
'Question2' => array(
'Option1', 'Option2', 'Option3'
),
'Question3' => array(
'Option1', 'Option2', 'Option3'
),
'Question4' => array(
'Option1', 'Option2', 'Option3'
)
),
'Category 2' => array(
'Question1' => array(
'Option1', 'Option2', 'Option3'
),
'Question2' => array(
'Option1', 'Option2', 'Option3'
)
),
'Category 3' => array(
'Question1' => array(
'Option1', 'Option2', 'Option3'
),
'Question2' => array(
'Option1', 'Option2', 'Option3'
),
'Question3' => array(
'Option1', 'Option2', 'Option3'
),
)
);
function fetchQuestions($survey, $page, $perPage = 3)
{
$results = Array();
$nCount = 0; $nRead = 0; $nIndex = $page * $perPage;
foreach ($survey as $CategoryName => $Questions)
{
foreach ($Questions as $Question => $Options)
{
if ($nCount >= $nIndex && $nRead < $perPage)
{
if (!isset($results[$CategoryName]))
$results[$CategoryName] = Array();
$results[$CategoryName][$Question] = $Options;
$nRead++;
}
$nCount++;
}
}
return $results;
}
echo '<html><body><pre>';
var_dump(fetchQuestions($survey,0));
var_dump(fetchQuestions($survey,1));
var_dump(fetchQuestions($survey,2));
echo '</pre></body></html>';
?>
And the output:
array(1) {
["Category1"]=>
array(3) {
["Question1"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
["Question2"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
["Question3"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
}
}
array(2) {
["Category1"]=>
array(1) {
["Question4"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
}
["Category 2"]=>
array(2) {
["Question1"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
["Question2"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
}
}
array(1) {
["Category 3"]=>
array(3) {
["Question1"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
["Question2"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
["Question3"]=>
array(3) {
[0]=>
string(7) "Option1"
[1]=>
string(7) "Option2"
[2]=>
string(7) "Option3"
}
}
}
There's my bid. Returns an array similar to your original array with the questions that should be displayed on that specific page.
If you want a more visual representation:
echo '<html><body>';
$page = 0;
while (count($matches = fetchQuestions($survey,$page++)) > 0)
{
echo '<div style="background-color:#CCC;">';
echo '<h2>Page '.$page.'</h2>';
echo '<ul>';
foreach ($matches as $Category => $Questions)
{
echo '<li><strong>'.$Category.'</strong>:<ul>';
foreach ($Questions as $Question => $Options)
{
echo '<li><u>'.$Question.'</u><ul>';
foreach ($Options as $Option)
echo '<li>'.$Option.'</li>';
echo '</ul>';
}
echo '</ul></li>';
}
echo '</ul>';
echo '</div>';
}
echo '</body></html>';
Related
I wanted to make an array as column from another array which representing like below. the column should be individual based on each index like , custom_text, thumb and title. I did more favor below.
array(6) {
[0]=>
array(1) {
["custom_text"]=>
string(15) "custom text 1"
}
[1]=>
array(1) {
["custom_text"]=>
string(18) "custom text 2"
}
[2]=>
array(1) {
["thumb"]=>
string(59) "image 1"
}
[3]=>
array(1) {
["thumb"]=>
string(59) "image 2"
}
[4]=>
array(1) {
["title"]=>
string(51) "title 1"
}
[5]=>
array(1) {
["title"]=>
string(181) "title 2"
}
}
here below code is for the array output
$th = array();
$allrows = array();
foreach($aawp_table['rows'] as $table_row_id => $table_row ){
if ( ! $table_row['status'] )
continue;
$th[] = array('headings' => $table_row['label']);
foreach ($aawp_table['products'] as $table_product_id => $table_product){
$asin = $aawp_table['products'][$table_product_id]['asin'];
$data = $aawp_table['products'][$table_product_id]['rows'][$table_row_id];
$type = $aawp_table['rows'][$table_row_id]['type'];
if ( 'custom_text' === $type ) {
$allrows[] = array(
'custom_text' => 'custom text'
);
}
if ( 'thumb' === $type ) {
$allrows[] = array(
'thumb' => 'thumb'
);
}
if('title' === $type){
$allrows[] = array(
'title' => 'title'
);
}
}
}
echo '<pre>';
var_dump($allrows);
echo '</pre>';
I want the array out like this as individual column
array(2) {
[0]=>
string() "custom text 1"
[1]=>
string() "image 1"
[2]=>
string() "custom text 2"
}
Can you please help to do it?
Let's iterate over the array you have and get all values for resulting array. Something like that.
<?php
$array = [
[
'custom_text' => 'custom text 1',
],
[
'custom_text' => 'custom text 2',
],
[
'thumb' => 'image 1',
],
[
'thumb' => 'image 2',
],
[
'title' => 'title 1',
],
[
'title' => 'title 2',
],
];
$result = [];
foreach ($array as $outterArray) {
foreach ($outterArray as $innerArrayValue) {
$result[] = $innerArrayValue;
}
}
var_dump($result);
The code snippet would generate the following output.
array(6) {
[0]=>
string(13) "custom text 1"
[1]=>
string(13) "custom text 2"
[2]=>
string(7) "image 1"
[3]=>
string(7) "image 2"
[4]=>
string(7) "title 1"
[5]=>
string(7) "title 2"
}
Instead of doing this
if ( 'custom_text' === $type ) {
$allrows[] = array(
'custom_text' => 'custom text'
);
}
if ( 'thumb' === $type ) {
$allrows[] = array(
'thumb' => 'thumb'
);
}
if('title' === $type){
$allrows[] = array(
'title' => 'title'
);
}
You should do this
if($type === 'title' || $type === 'thumb' || $type === 'custom_text'){
array_push($allrows,$type);
}
I have an array with name $items like this:
array(2) {
[0]=> array(8) { ["item_regel"]=> int(0) ["item_id"]=> string(2) "82" ["item_naam"]=> string(21) "Bureauschermen staand" ["item_uitvoering"]=> string(12) "100 x 200 cm" ["item_afmeting"]=> NULL ["item_kleur"]=> string(11) "Transparant" ["item_aantal"]=> string(1) "2" ["item_opmerking"]=> string(18) "Ik wil mijn logo 2" }
[1]=> array(8) { ["item_regel"]=> int(1) ["item_id"]=> string(3) "226" ["item_naam"]=> string(33) "Instructieborden Dibond aluminium" ["item_uitvoering"]=> string(10) "50 x 50 cm" ["item_afmeting"]=> NULL ["item_kleur"]=> string(5) "Blauw" ["item_aantal"]=> string(1) "2" ["item_opmerking"]=> string(4) "test" }
}
I found this code to prefill a gravity form list field:
add_filter( 'gform_field_value_list_one', 'itsg_prefill_list_one' );
function itsg_prefill_list_one( $value ) {
$list_array = array(
//List row
array(
"Product" => "Product",
"Afmeting" => "Good",
"Uitvoering" => "Product",
"Kleur" => "Product",
"Aantal" => "Product",
"Opmerking" => "Product",
),
//List row
array(
"Product" => "Product",
"Afmeting" => "Good",
"Uitvoering" => "Product",
"Kleur" => "Product",
"Aantal" => "Product",
"Opmerking" => "Product",
),
);
return $list_array;
}
Now this function is filled with fixed values. I want to do a 'List row' foreach row inside the array above.
I tried this but it won't work:
add_filter( 'gform_field_value_list_one', 'itsg_prefill_list_one' );
function itsg_prefill_list_one( $value ) {
$items = $_SESSION["wishlist"];
$list_array = array(
foreach ($items as $keys => $values) {
array(
"Product" => $values["item_naam"],
"Afmeting" => $values["item_afmeting"],
"Uitvoering" => $values["item_uitvoering"],
"Kleur" => $values["item_kleur"],
"Aantal" => $values["item_aantal"],
"Opmerking" => $values["item_opmerking"],
),
}
);
return $list_array;
}
Inside the loop add items to the array from the looped array
add_filter( 'gform_field_value_list_one', 'itsg_prefill_list_one' );
function itsg_prefill_list_one( $value ) {
foreach ($_SESSION["wishlist"] as $keys => $values) {
$list_array[] = [
"Product" => $values["item_naam"],
"Afmeting" => $values["item_afmeting"],
"Uitvoering" => $values["item_uitvoering"],
"Kleur" => $values["item_kleur"],
"Aantal" => $values["item_aantal"],
"Opmerking" => $values["item_opmerking"],
];
}
return $list_array;
}
I have the following code. This fetches fields from an SQL table ("db") and prepares them for use in a datatable ("dt").
$columns = array(
array( 'db' => 'Author', 'dt' => 'authors'),
array( 'db' => 'Editor', 'dt' => 'editor')
);
It prints this
[{"authors":"John Smith; Paul Phillips","editors":"Robert Fox"},...]
Now I would like to push a third array (people) to columns, one that combines the previous two arrays, but without replacing them, like
[{"authors":"John Smith; Paul Phillips","editors":"Robert Fox","people": "John Smith: Paul Phillips; Robert Fox"},...]
If its just an array that you try to add to $columns,
Use array_merge()
$columns = array(
array( 'db' => 'Author', 'dt' => 'authors'),
array( 'db' => 'Editor', 'dt' => 'editor')
);
$person = array( 'db' => 'Person', 'dt' => 'person');
$newArray = array_merge($columns, $person);
The outcome should look like this:
array(4) {
[0]=>
array(2) {
["db"]=>
string(6) "Author"
["dt"]=>
string(7) "authors"
}
[1]=>
array(2) {
["db"]=>
string(6) "Editor"
["dt"]=>
string(6) "editor"
}
[2]=>
array(2) {
["db"]=>
string(6) "Person"
["dt"]=>
string(6) "person"
}
}
I need to sort a multidimensional array by a searched keyword.
My array is like below.
<?php
array(
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
)
?>
I need to sort this array when search keyword is physics . And after Sorting i need the result like below.
NEEDED RESULT
<?php
array(
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
)
?>
That is I need to sort the array first by the name which is exactly like the searched keyword. Then wildcard search in name. Then to the next key branch and same as above. Is there any php function to sort this array like my requirement. I have already checked asort, usort. But I didn't get result properly.
Just call this simple function I just created for your requirement, It works just fine :) change the priority order according to your need
function sortArray($array,$itemToSearch)
{
$sortedArray = array();
$priorityOrder = ['name','branch','college'];
foreach ($priorityOrder as $key)
{
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) === 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) > 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
}
return $sortedArray;
}
Here we go
So I started from the algorithm in this answer and modified it to fit your requirements. Since you have three different "priorities" to you sorting, we have to use some temporary variables to separate the elements we wish sorted.
// arrays used to separate each row based on the row where the word "Physics" is found
$searchName = array();
$searchBranch = array();
$searchCollege = array();
// arrays used later for array_multisort
$foundInName = array();
$foundInBranch = array();
$foundInCollege = array();
foreach ($var as $key => $row) {
if(strpos(strtolower($row['name']), 'physics') !== false) {
$searchName[$key] = $row['name'];
$foundInName[] = $row;
}
elseif(strpos(strtolower($row['branch']), 'physics') !== false) {
$searchBranch[$key] = $row['branch'];
$foundInBranch[] = $row;
}
elseif(strpos(strtolower($row['college']), 'physics') !== false) {
$searchCollege[$key] = $row['college'];
$foundInCollege[] = $row;
}
}
// Note: I use SORT_NATURAL here so that "11-XXXXX" comes after "2-XXXXX"
array_multisort($searchName, SORT_NATURAL, $foundInName); // sort the three arrays separately
array_multisort($searchBranch, SORT_NATURAL, $foundInBranch);
array_multisort($searchCollege, SORT_NATURAL, $foundInCollege);
$sortedArray = array_merge($foundInName, $foundInBranch, $foundInCollege);
Outputting $sortedArray using var_dump() gives something like:
array(5) {
[0]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[1]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[2]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
As you can see 11th-Physics comes out first. That is because the ASCII value of numbers is lower than that of letters. To fix this, modify the $search... arrays by prepending a high ASCII character before the string.
if(strpos(strtolower($row['name']), 'physics') !== false) {
// if the first character is a number, prepend an underscore
$searchName[$key] = is_numeric(substr($row['name'], 0, 1)) ? '_'.$row['name'] : $row['name'];
$foundInName[] = $row;
}
Which yields the following output:
array(5) {
[0]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[1]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[2]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
Try it here!
This is my array:
array(4) {
["1"]=>
array(3) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
[2]=>
string(2) "03"
}
["2"]=>
array(2) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
}
["3"]=>
array(1) {
[0]=>
string(2) "01"
}
["4"]=>
array(1) {
[0]=>
string(2) "01"
}
}
I want to print the lowest key, but only from the keys, that have less than 3 values.
echo min(array_keys($myarray));
gives me the result: 1
But key 1 already has 3 values, so the result I would need is 2. In the case every key has 3 values then print the next key (in this case would be 5)
I do not know how to do this. I am happy for every hint or advise.
This function iterate over your array and looks for all keys that has a value less then 3 values. It will return the first it founds if none is found the next key is return.
function getLowestKeyWithLessThan($yourArray, $number=3)
{
foreach ($yourArray as $key => $value) {
if (count($value) < $number)
return $key;
}
return count($yourArray) + 1;
}
If I run the following lines:
print "Answer " . getLowestKeyWithLessThan($yourArray);
print "\nAnswer " . getLowestKeyWithLessThan($AllKeysHasThreeElements);
This gives the answer:
Answer 2
Answer 5
Here is the data I used to test this:
$yourArray = array(
"1"=> array(
'0' => "01",
'1' => "02",
'2' => "03",
),
"2"=> array(
'0' => "01",
'1' => "02",
),
"3"=> array(
'0' => "01",
),
"4"=> array(
'0' => "01",
),
);
$threeValues = array(
'0' => "01",
'1' => "02",
'2' => "03",
);
$AllKeysHasThreeElements = array(
"1"=> $threeValues,
"2"=> $threeValues,
"3"=> $threeValues,
"4"=> $threeValues,
);
Of course the data could also been written like this:
$threeValues = array("01", "02", "03");
$yourArray = array($threeValues, array("01", "02"), array("01"), array("01"));
$AllKeysHasThreeElements = array($threeValues,$threeValues,$threeValues,$threeValues);