How can I print the lowest key of an array? - php

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

Related

array_combine results only one result [duplicate]

This question already has answers here:
array_combine is return only last value
(2 answers)
Closed 3 years ago.
I am using the following code to get two arrays into one json result. But getting only the first index as result. Is there any error in the code or anybody can suggest an alternate method to get the same result.
$array1 = $_POST['array1'];
$array2 = $_POST['array2'];
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
$_POST['array1'] = array(4) {
[0]=>
string(3) "day1"
[1]=>
string(3) "day2"
[2]=>
string(3) "day3"
[3]=>
string(3) "day4"
}
$_POST['array2'] = array(4) {
[0]=>
string(3) "item1"
[1]=>
string(3) "item2"
[2]=>
string(3) "item3"
[3]=>
string(3) "item4"
}
Expected result should be like
[{"name":"day1","value":"item1"},{"name":"day2","value":"item2"},{"name":"day3","value":"item3"}]
Try this,
$arr1 = array('0' => 'day1', '1' => 'day2', '2' => 'day3', '3' => 'day4');
echo'<pre>';print_r($arr1);
$arr2 = array('0' => 'item1','1' => 'item2','2' => 'item3','3' => 'item4');
echo'<pre>';print_r($arr2);
echo'<pre>';print_r(array_combine($arr1, $arr2));
$newArray = array();
foreach(array_combine($arr1, $arr2) as $key => $value){
array_push($newArray, array('name'=> $key,'value'=>$value));
}
echo'<pre>';print_r($newArray);
echo json_encode($newArray);die;

Sort Multidimensional Array By Searched Word

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!

How to compare two multidimensional arrays by certain keys in each?

I have two multidimensional arrays of the same structure.
Like this:
array(2) {
[0] =>
array(9) {
'id' =>
string(5) "44994"
'ersatzteil_id' =>
string(3) "120"
'lang' =>
string(6) "name2_tag2"
'title' =>
string(12) "Seitentüren"
'alias' =>
string(12) "seitentueren"
'content' =>
string(1610) "LOREM ISPUM BLALABLBL"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "1"
'short_text' =>
NULL
}
[1] =>
array(9) {
'id' =>
string(5) "44996"
'ersatzteil_id' =>
string(3) "122"
'lang' =>
string(6) "name1_tag1"
'title' =>
string(7) "Spoiler"
'alias' =>
string(7) "spoiler"
'content' =>
string(1513) "SOME OTHER RANDOM TEXT"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "0"
'short_text' =>
NULL
}
}
What I need to do is I need to compare first array with the second one.
I have to compare them by keys ersatzteil_id and content , and I find that they have same content I need to store element from first array in another new array, that wasn't existing before.
For example I need something like this, but more efficient:
if(array1[20]['ersatzteil_id'] == array2[145]['ersatzteil_id']
&& array1[20]['content'] == array2[145]['content']){
array3 = array1[20];
}
Try this code:-
$result = [];
foreach($array1 as $arr1){
foreach($array2 as $arr2){
if(($arr1['id'] == $arr2['id']) && ($arr1['ersatzteil_id'] == $arr2['ersatzteil_id'])){
$result[] = $arr1;
}
}
}
echo '<pre>'; print_r($result);

Combining two arrays with unique field

Combining A array and B array and want the result show below
EDITED
a = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val1"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val1"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val1"]=> string(2) "79"
}
}
b = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val2"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val2"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val2"]=> string(2) "79"
}
[3]=> array(2) {
["pid"]=> string(2) "61"
["val2"]=> string(1) "1"
}
[4]=> array(2) {
["pid"]=> string(2) "62"
["val2"]=> string(2) "24"
}
}
Need help.
If this is coming from a data source, see if there's a way you can do this outside of PHP (e.g. MySQL's JOIN).
If PHP is your only answer, then below is a solution. Note that I changed the values of val1 and val2 so it was a bit more distinguishable.
You must have some sort of grouping constraint, which is configurable in the script below via $groupByKey. Judging by the common occurrence of PID, I assumed this as the subject key.
Also, if you have more than two arrays all following a similar schema (I have commented out $c as an example), you simply add more arguments to array_merge.
The idea is to keep merging each item in the cumulative list by using a fixed key as a "pointer," if you will.
<?php
$a = array(
array('pid' => 1, 'val1' => 'alpha'),
array('pid' => 3, 'val1' => 'bravo'),
array('pid' => 4, 'val1' => 'charlie')
);
$b = array(
array('pid' => 3, 'val2' => 'delta'),
array('pid' => 5, 'val2' => 'echo'),
array('pid' => 1, 'val2' => 'foxtrot'),
array('pid' => 8, 'val2' => 'golf')
);
/*
$c = array(
array('pid' => 3, 'val3' => 'hotel'),
array('pid' => 5, 'val1' => 'india'),
array('pid' => 1, 'val3' => 'juliette'),
array('pid' => 8, 'val3' => 'kilo')
);
*/
$groupByKey = 'pid'; // this becomes the fixed key
$merged = array_merge($a,$b); // array_merge($a,$b,$c); // cumulative container of all items in every subject array
$result = array(); // the result will be stored here, e.g. a temporary "table"
foreach ( $merged as $item ) { // $merged is essentially a table of subjects and $item is each row
if ( !isset($result[$item[$groupByKey]]) ) { // if we haven't come across this key yet
$result[$item[$groupByKey]] = array(); // initialize it
}
$result[$item[$groupByKey]] = array_merge($result[$item[$groupByKey]],$item); // consolidate all the cells for this row, later duplicate keys will cause values to be replaced
}
$result = array_values($result); // normalize the result keys, for the view they should increment rather than represent the group-by subjects
var_dump($result); // let's see how we did
?>
Provides:
array (size=5)
0 =>
array (size=3)
'pid' => int 1
'val1' => string 'alpha' (length=5)
'val2' => string 'foxtrot' (length=7)
1 =>
array (size=3)
'pid' => int 3
'val1' => string 'bravo' (length=5)
'val2' => string 'delta' (length=5)
2 =>
array (size=2)
'pid' => int 4
'val1' => string 'charlie' (length=7)
3 =>
array (size=2)
'pid' => int 5
'val2' => string 'echo' (length=4)
4 =>
array (size=2)
'pid' => int 8
'val2' => string 'golf' (length=4)

Clean up php array via alphabetical keys

I am extracting data from an xls document which returns as an array. The array keys however is not numeric, but resembles the cell column alphabetical digit. So effectively I have an array like this:
// Example array:
$array = array(
[0] => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
[1] => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
[2] => array(
"A" => "",
"B" => "",
"C" => "",
"D" => ""
)
);
Now the problem with the returned array is it does not filter the array at all, and I may have rows and rows of empty values in the rows.
I need a way to either clean up the array completely so remove empty rows and digits, but this may give me some issues with array consistancy later.
What I am looking for is a function which can chop rows in an array by a alphebitical digit. So effectively something like array_chop($array","C"); which would then effectively unset all the remainder rows key and value pairs from D onwards.
Is this possible? Is there a php function already I can use? I am sorry that I cannot provide sample code but I have no idea where to start. The array is substancially large, so I am looking for a memory efficient solution.
Thank you in advance!
If you want to copy only a small first portion of the column, this must be efficient:
<?php
$array = array(
0 => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
1 => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
2 => array(
"A" => "",
"B" => "",
"C" => "",
"D" => ""
)
);
$last_column = 1;
$n = count($array);
for ($i = 0; $i < $n; ++$i)
{
$copy = array();
$j = 0;
foreach($array[$i] as $key => $value)
{
if ($j <= $last_column)
{
$copy[$key] = $value;
++$j;
}
else
{
$array[$i] = $copy;
break;
}
}
}
var_dump($array);
This leaves only name and surname in the matrix:
array(3) {
[0]=>
array(2) {
["A"]=>
string(4) "Name"
["B"]=>
string(7) "Surname"
}
[1]=>
array(2) {
["A"]=>
string(4) "Name"
["B"]=>
string(7) "Surname"
}
[2]=>
array(2) {
["A"]=>
string(0) ""
["B"]=>
string(0) ""
}
}

Categories