json array elements to array - php

$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

Related

Multidimensional Array Search by Multiple Keys given as Variable?

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.

PHP adding values inside multidimensional array

Please find below the code sample for adding repeated values inside inner array. Can anyone suggest an alternative way to add the values faster? The code will work with smaller arrays, but I want to add big arrays that contain huge amount of data. Also I want to increase execution time.
<?php
$testArry = array();
$testArry[0] = array(
"text" => "AB",
"count" => 2
);
$testArry[1] = array(
"text" => "AB",
"count" => 5
);
$testArry[2] = array(
"text" => "BC",
"count" => 1
);
$testArry[3] = array(
"text" => "BD",
"count" => 1
);
$testArry[4] = array(
"text" => "BC",
"count" => 7
);
$testArry[5] = array(
"text" => "AB",
"count" => 6
);
$testArry[6] = array(
"text" => "AB",
"count" => 2
);
$testArry[7] = array(
"text" => "BD",
"count" => 111
);
$match_key = array();
$final = array();
foreach ($testArry as $current_key => $current_array) {
$match_key = array();
foreach ($testArry as $search_key => $search_array) {
$key = '';
if ($search_array['text'] == $current_array['text']) {
$match_key[] = $search_key;
$key = $search_array['text'];
if (isset($final[$key])) {
$final[$key] += $search_array['count'];
} else {
$final[$key] = $search_array['count'];
}
}
}
for ($j = 0; $j < count($match_key); $j++) {
unset($testArry[$match_key[$j]]);
}
}
print_r($final);
?>
Anyway to add memory during the execution time?
Thank you.
One array_walk will be enough to solve your problem,
$final = [];
array_walk($testArry, function($item) use(&$final){
$final[$item['text']] = (!empty($final[$item['text']]) ? $final[$item['text']] : 0) + $item['count'];
});
print_r($final);
Output
Array
(
[AB] => 15
[BC] => 8
[BD] => 112
)
Demo
array_walk — Apply a user supplied function to every member of an array
array_map() - Applies the callback to the elements of the given arrays
array_key_exists() - Checks if the given key or index exists in the array
You can use array_walk and array_key_exists to iterate through the array element and sum the one which has text index same
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['text'], $res) ? ($res[$v['text']] += $v['count']) : ($res[$v['text']] = $v['count']);
}, $testArry);

Re-index numeric nested arrays keys

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
)

Combine post values and remove empty

I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
[0] => First
[1] => Second
[2] =>
[3] => Fourth
)
$_POST[numbers]
(
[0] => 10
[1] =>
[2] => 3
[3] => 3
)
Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
[First] => 10
[Fourth] => 3
)
Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
$names = array_filter($_POST['names']);
$numbers = array_filter($_POST['numbers']);
if($names and $numbers) {
$final = array_combine($names, $numbers);
}
}
But I can't seem to filter it correctly, since its giving me an error:
Warning: array_combine(): Both parameters should have an equal number of elements
How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
$array1 = [
0 => "First",
1 => "Second",
2 => "",
3 => "Fourth",
];
$array2 = [
0 => 10,
1 => "",
2 => 3,
3 => 3,
];
var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
return $key == "" || $value == "" ? false : $value;
}, ARRAY_FILTER_USE_BOTH ));
/*
Output:
array(2) {
["First"]=>
int(10)
["Fourth"]=>
int(3)
}
*/
Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
$_POST['numbers']))));
// create array using $_POST['names'] as keys and $_POST['numbers'] as values
$result = array_combine($_POST['names'], $_POST['numbers']);
// remove entries that have empty values
$result = array_filter($result);
// remove entry with empty key
unset($result[null]);
print_r($result);
If both arrays will have the same count, and the keys will always be numeric, you could do the following:
$total = count($_POST['names']);
$final = array();
for ($i = 0; $i < $total; $i++) {
if (trim($_POST['names'][$i]) != '' && trim($_POST['numbers'][$i]) != '') {
$final[$_POST['names'][$i]] = $_POST['numbers'][$i];
}
}
Or if you prefer to use a foreach instead of for
$final = array();
foreach ($_POST['names'] as $key => $value) {
if (trim($value) != '' && trim($_POST['numbers'][$key]) != '') {
$final[$value] = $_POST['numbers'][$key];
}
}
Takeing your previous information into account:
both keys will be numeric and the count will be the same, since they come in pairs as names and numbers
$myNewArray = array();
$count = 0;
foreach ($_POST['names'] as $bufferArray)
{
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL))
{
array_push($myNewArray, array($bufferArray[$count] => $_POST['numbers][$count]);
}
$count++;
}
Let me know if that helps! :)
Note: I made some edits to the code.
Also, my previous code checks if the empty array spaces are NULL. If you want to check if they are either NULL or "" (empty), then replace the line of code with:
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL)&&($bufferArray[$count]!="")&&($_POST['numbers][$count]!=""))
{...}

How do you Change Array Index Keys to MySQL values

I need help working with arrays. I have an array of data from a MySQL query. After printing it in a for loop, I get the following array_flip:
Array (
[Duru 60] => 0
[Maxwell 50] => 1
[Fashanu 70] => 2
[Nwankwo 80] => 3
[Obi 0] => 4
)
The array value is a combination of 2 fields name and total score. What I want to achieve is an array like so:
Array (
[Duru 60] => 60
[Maxwell 50] => 50
[Fashanu 70] => 70
[Nwankwo 80] => 80
[Obi 0] => 0
)
What I want to achieve is to change the default array numeric keys (0,1,2,3,4) to total score obtained from the query.
Here is the code that gave the first array block:
PHP code begins
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
array_push($dataA,($dataC));
}
$dataD = (array_flip($dataA));
print_r($dataD);
$dataA = array();
foreach($data as $key => $val){
$dataK = $val['lastname']." ".$val['total'];
$dataV = $val['total'];
$dataA[$dataK] = $dataV;
}
print_r($dataA);
Try this:
$dataA = array();
foreach($data as $key => $val){
$dataC = $val['lastname']." ".$val['total'];
$dataA[$dataC] = $val['total'];
}
print_r($dataA);
Why can't you just do:
$newData = array();
foreach($data as $key => $val) {
$newData[$val['lastname'] . ' ' . $val['total']] = $val['total'];
}
print_r($newData);

Categories