I have a multidimensional array which has keys and key has values or have another array with keys and values so I want to search by keys but in input like 230 is user input
and it will go to 3 then 4 then 1 if result is a value but not an array it must print the value like
input = 230 result should be = "3-4-1"
so I need to str_split the number and search it 1 by 1 if first number is array then look for second kinda
edit1 = I found the way to split the key
//edit1
$keys = "021";
$keysSplit =str_split($keys, strlen($keys)/strlen($keys));
echo $keys[0];
//edit 1 ends
$arr = [0 => [0=>"1-1", 1 => "1-2" , 2=>"1-3", 3=>[0=>"1-4-1", 1 => "1-4-2" , 2=>"1-4-3"]],
1 => [0=>"2-1", 1 => "2-2" , 2=>"2-3"],
2 => [0=>"3-1", 1 => "3-2" , 2=>"3-3", 3=>[0 =>"3-4-1" , 1=> "3-4-2"]],
];
$keys = "021";
function searchByKey($array , $keys){
$result = [];
$keys = "021";
$keys =str_split($keys, strlen($keys)/strlen($keys));
$key1 = $keys[0];
$key2 = $keys [1];
$key3 = $keys [2];
foreach ($array as $key1 => $value){
if (is_array($value)){
$key1 = null;
$key1 = $key2;
$key2 = $key3;
return searchByKey($value , $key1);
}
else {
$result=$value;
echo $result;
}
}
}
$arr = searchByKey($arr, $keys);
The function only works as key and value given and it will print every key and value on the key it asked first so its not the thing I wanted to do could anyone help and explain?
Answer given by #Anggara I made it in to function ;
$input = "11";
function searchByNumber($array, $input){
$result = $array;
for ($i = 0; $i < strlen($input); $i++) {
if (is_array($result)) {
$result = $result[$input[$i]];
} else {
$result = "Does not exists";
break;
}
}
echo $result;
}
$arr = searchByNumber($arr, $input);
You can access char in string like accessing an array. For example:
$input = "230";
// $input[0] is "2"
// $input[1] is "3"
// $input[2] is "0"
So my approach is to loop for each character in input key, and look for corresponding value in $arr. Each iteration will set found array element into variable $result. If the searched key does not exist (ex: "021"), print error message.
<?php
$arr = [
0 => [
0 => "1-1",
1 => "1-2",
2 => "1-3",
3 => [
0 => "1-4-1",
1 => "1-4-2",
2 => "1-4-3"
]
],
1 => [
0 => "2-1",
1 => "2-2",
2 => "2-3"
],
2 => [
0 => "3-1",
1 => "3-2",
2 => "3-3",
3 => [
0 => "3-4-1",
1 => "3-4-2"
]
],
];
$input = "230";
$result = $arr;
for ($i = 0; $i < strlen($input); $i++) {
if (is_array($result)) {
$result = $result[$input[$i]];
} else {
$result = 'Can not traverse path';
break;
}
}
echo $result;
After splitting the keys
for($i=0;$i<strlen($keys);$i++){
$arr = $arr[$keys[$i]];
}
if(is_array($arr)){
echo json_encode($arr);
}else{
echo $arr;
}
You need a loop, which will go through the keys one by one and assigning into the array.
Related
I have two txt files with the same length (10 lines in each). One file has IDs, and the other has a "rating" (0, 1, 2, etc) that is associated with each ID. For example:
txt 1 | txt 2
123 | 1
234 | 2
etc.
I want to replace the rating when I provide an ID.
What I did was search the key associated with the provided ID and when it matches the key in the ratings array I replace the corresponding value in the ratings array.
So the idea is find key for '123' in ids (key=0) and replace the rating value with key=0 (in this case 1) for another value.
I have the following in a function:
public function updateRating($disease, $id, $rating){
$filename = $disease.".txt";
$filename_2 = $disease."Ratings.txt";
$ids = file($filename);
$ratings = file($filename_2);
$index_ids = array_keys($ids, $id."\n");
$index_ratings = array_keys($ratings);
$size = count($ids);
for($i=0; $i<$size; $i++){
if($index_ratings[$i] == $index_ids){
$ratings = str_replace($ratings[$i], $rating."\n", $ratings);
}
}
$ratings_n = implode("", $ratings);
file_put_contents($filename_2, $ratings_n);
return array("debug2" => $index_ids, "debug3" => $index_ratings, "debug4" => $ratings);
The index_ids (the key for the provided ID) is being returned correctly, but the array for the ratings ($ratings) is returned as if nothing was replaced. What is wrong in this code and how can I correct it to do what I want it to do?
Use array_search() in your function to get the key:
https://paiza.io/projects/zdg_xzGwV8KfgOqkzeCgjA
function replaceValue($value, $arr1, &$arr2){
$key = array_search($value, $arr1);
if($key === false){
return false;
}else{
$arr2[$key] = $value;
return true;
}
}
if(replaceValue("baz", $arr1, $arr2)){
print_r($arr2);
}else{
echo "no match found";
}
Result:
Array
(
[x] => bizz
[y] => bazz
[c] => baz
)
You can follow this kind of steps to achieve the result
<?php
$arr1 = [0 => '123', 1 => '234'];
$arr2 = [0 => 'a', 1 => 'b'];
for ($i=0; $i < sizeof($arr1) ; $i++) {
for ($i=0; $i < sizeof($arr1) ; $i++) {
if ($arr1[$i] == '123') {
$arr2[$i] = 'abc';
}
}
}
echo'<pre>';
print_r($arr2);
echo '<pre>';
?>
Output
Array
(
[0] => abc
[1] => b
)
$cuisines = RestaurantProfile::select('cuisines')->get();
$cuisines_array = array();
foreach ($cuisines as $cuisine) {
$string = implode(",",json_decode($cuisine, true));
$array = explode(",", $string);
foreach ($array as $single) {
if (!in_array($single, $cuisines_array)) {
$cuisines_array[] = $single;
}
}
}
dd($cuisines_array);
I want $cuisines_array to have something like
array:33 [▼
0 => "Afghani"
1 => "Mughlai"
2 => "Chinese"
3 => "Indian"
4 => "continental"
5 => "south indian"
6 => "mughlai"
But I am getting as in the screenshot: output screenshot
My Cuisines attribute in table is database table.
Any leads?
You can use array_slice() :
...
foreach (array_slice($array, 0, 6) as $single) {
...
array_slice()
returns the sequence of elements from the array array as specified by
the offset and length parameters
Here is my array:
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
I need to restart all keys and start all of them from 0. Based on some researches, I figured out I have to use array_values() function. But it just makes the keys of outer array re-index, See.
How can I apply it on the all keys of array? (even nested ones)
You can use array_values + recursively calling custom function:
function arrayValuesRecursive($array) {
$array = array_values($array);
$countValues = count($array);
for ($i = 0; $i < $countValues; $i++ ) {
$subElement = $array[$i];
if (is_array($subElement)) {
$array[$i] = arrayValuesRecursive($subElement);
}
}
return $array;
}
$restructuredArray = arrayValuesRecursive($array);
You can implement it using recursion like this:
function reIndex($arr) {
$arr = array_values($arr);
foreach ($arr as $k => $v) {
if (is_array($v)) {
$arr[$k] = reIndex($v);
}
}
return $arr;
}
$arr = reIndex($arr);
Hi checkout following code
<?php
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
$reIndexedArray = array();
foreach($arr as $arrItr){
$reIndexedArray[] = count($arrItr) > 1 ? array_values($arrItr) : $arrItr;
}
print_r($reIndexedArray);
?>
output is
Array
(
[0] => Array
(
[0] => something
[1] => something else
)
[1] => foo br
)
I want to check data in array to see if there are null values. If there are, I'd like to display an alert.
Example:
$data = array(1 => 'AKB48', 2 => '', 3 => 'JKT48');
The Array of index 1 ($data[1]) is null, and I want it to display "WARNING, data in array is null"
if data in array does not have empty/null values then don't show an alert:
$data = array(1 => 'AKB48', 2 => 'HKT48', 3 => 'JKT48');
(the above array will no trigger an alert)
How can I achieve this solution?
something like this?
$data = array(1 => 'AKB48', 2 => '', 3 => 'JKT48');
foreach($data as $val) {
if($val == '') {
echo "alert, array consist of empty value";
}
}
$data = array(1 => 'AKB48', 2 => '', 3 => 'JKT48');
foreach($data as $v)
{
if(empty($v))
{
echo "Array contains null value";
break;
}
}
Something like this?
isDefined will check if the value is a valid non-empty String.
function isDefined($var) {
return isset($var) && !is_null($var) && !empty($var);
}
$data = array(
array('AKB48', 'HKT48', NULL),
array('AKB49', '', 'JKT49'),
array('AKB50', 'HKT50', 'JKT50')
);
for ($i = 0; $i < count($data); $i++) {
foreach ($data[$i] as $col) {
if (!isDefined($col)) {
echo "<<<Attention: Array #$i contains an empty value!>>> ";
}
}
}
Running example of code above.
I'm working on a leader board that pulls the top scorers into first, second, and third place based on points. Right now I'm working with a sorted array that looks like this (but could be of infinite length with infinite point values):
$scores = Array
(
["bob"] => 20
["Jane"] => 20
["Jill"] => 15
["John"] => 10
["Jacob"] => 5
)
I imagine I could use a simple slice or chunk, but I'd like to allow for ties, and ignore any points that don't fit into the top three places, like so:
$first = Array
(
["bob"] => 20
["Jane"] => 20
)
$second = Array
(
["Jill"] => 15
)
$third = Array
(
["John"] => 10
)
Any ideas?
$arr = array(
"Jacob" => 5,
"bob" => 20,
"Jane" => 20,
"Jill" => 15,
"John" => 10,
);
arsort($arr);
$output = array();
foreach($arr as $name=>$score)
{
$output[$score][$name] = $score;
if (count($output)>3)
{
array_pop($output);
break;
}
}
$output = array_values($output);
var_dump($output);
$first will be in $output[0], $second in $output[1] and so on.. Code is limited to 3 first places.
ps: updated to deal with tie on the third place
I would do something like:
function chunk_top_n($scores, $limit)
{
arsort($scores);
$current_score = null;
$rank = array();
$n = 0;
foreach ($scores as $person => $score)
{
if ($current_score != $score)
{
if ($n++ == $limit) break;
$current_score = $score;
$rank[] = array();
$p = &$rank[$n - 1];
}
$p[$person] = $score;
}
return $rank;
}
It sorts the array, then creates numbered groups. It breaks as soon as the limit has been reached.
You can do it with less code if you use the score as the key of the array, but the benefit of the above approach is it creates the array exactly how you want it the first time through.
You could also pass $scores by reference if you don't mind the original getting sorted.
Here's my go at it:
<?php
function array_split_value($array)
{
$result = array();
$indexes = array();
foreach ($array as $key => $value)
{
if (!in_array($value, $indexes))
{
$indexes[] = $value;
$result[] = array($key => $value);
}
else
{
$index_search = array_search($value, $indexes);
$result[$index_search] = array_merge($result[$index_search], array($key => $value));
}
}
return $result;
}
$scores = Array(
'bob' => 20,
'Jane' => 20,
'Jill' => 15,
'John' => 10,
'Jacob' => 5
);
echo '<pre>';
print_r(array_split_value($scores));
echo '</pre>';
?>