$firstArray= [
[
"ID" => "ABC"
],
[
"ID" => "100"
],
[
"ID" => "200"
]
];
$firstArray= ["ABC" =>"fail"];
**Here I have to check two condition**
Condition #1
$abc i am having 3 values, out of this values suppose present in $second array,we have ignore the value and remaining only one value we have to assign $existarray
As of now i have completed it is working fine also,
Condition #2
I have one more json like this
$jsonString = '{
"jsonData" : {
"ABC" : {
"Count" :1
},
"100" : {
"Count" :3
},
"200" : {
"Count" :1
}
}
}';
$finalcount= json_decode($jsonString);
Now i want to check one more condition $abc array of mainarray key values count <10 we should ignore.This condition i have to implement my current code
Expected output
Array
(
[ID] => 200
)
Merging 2 condition in if statement is done with &&.
You can just mix those 2 condition in 1 for-loop:
$jsonString = '{"jsonData" : {
"ABC" : {"Count" :1},
"100" : {"Count" :3},
"200" : {"Count" :1}
}
}';
$firstArray = json_decode($jsonString, true);
$hobbies= [["ID" => "ABC"],["ID" => "100"],["ID" => "200"]];
$books= ["ABC" => true];
foreach ($Response as $key => $value) {
$id = $value['ID'];
if (!isset($books[$id]) && $firstArray["jsonData"][$id]["Count"] < 3 ) {
$selectedItem = $value;
break;
}
}
Related
I need to group values in my flat array so that each non-integer value starts a new group/row in my result array and every integer value encountered until the next occurring non-integer should be pushed into a subarray in the respective group/row.
Input:
$unitsList = [
"Aulas Gratuitas",
"149",
"151",
"153",
"Módulo 0",
"964",
"989",
"Módulo 1",
"985",
"1079",
"1001",
"1003"
"Módulo 2",
"1009"
];
Current code:
$newArr = array();
foreach( $unitsList as $item ) {
if( !is_numeric($item) ) {
$title = array( "title" => $item, "units" => "" );
array_push( $newArr, $title);
} elseif ( is_numeric($item) ) {
$number = $item;
array_push( $newArr, $number);
}
}
Current result:
[
[
"title" => "Aulas Gratuitas",
"units" => ""
]
"149",
"151",
"153",
[
"title" => "Módulo 0",
"units" => ""
],
"964",
"989",
[
"title" => 'Módulo 1',
"units" => ""
],
"985",
"1079",
"1001",
"1003"
[
"title" => 'Módulo 2',
"units" => ''
],
"1009"
]
As you can see, I am having a hard time adding the numbers into the "units" key.
Desired result:
[
[
"title" => "Aulas Gratuitas",
"units" => ["149", "151", "153"]
],
[
"title" => 'Módulo 0',
"units" => ["964", "989"]
],
[
"title" => 'Módulo 1',
"units" => ["985", "1079", "1001", "1003"]
],
[
"title" => "Módulo 2",
"units" => ["1009"]
]
]
So that you don't need to keep track of first level indexes, use a reference variable and push related data into that AFTER pushing the new row into the result array.
Code: (Demo)
$result = [];
foreach ($array as $value) {
if (!ctype_digit($value)) {
unset($units);
$units = [];
$result[] = ['title' => $value, 'units' => &$units];
} else {
$units[] = $value;
}
}
var_export($result);
unset() is used to destroy the reference to the previous group, otherwise newly pushed data would be sent to two (or more) places in the result array.
Reference variables have a default value of null. If your title values are guaranteed to be followed by an integer/unit value, then $units = []; can be removed. If you have a title and then another title there will be no data for the former title group. With the explicit array declaration, the group will have an empty units array instead of null.
Related questions answered with the same general technique:
Group array of objects into deeper parent-child structure
Split flat array into grouped subarrays containing values from consecutive key in the input array
How to split a string by repeated characters in PHP?
If you are running PHP7.3 or higher (and by this point you definitely should be) AND you are intimidated/mystified by using a reference variable, then you can leverage array_key_last() to locate the latest created array row.
Code: (Demo)
$result = [];
foreach ($array as $value) {
if (!ctype_digit($value)) {
$result[] = ['title' => $value, 'units' => []];
} else {
$result[array_key_last($result)]['units'][] = $value;
}
}
var_export($result);
Items in the given list aren't regular. The first item has three units, and the second has two units. We cannot convert them into the expected structure without controlling the type of each item. My solution is below. I added explanations as a comment line.
$values = array(
"string",
11111,
22222,
33333,
"string_2",
44444,
55555
);
$formattedArray = [];
$index = -1;
foreach ($values as $value) {
// If the value is a string, create the new array structure item and assign the title
if (is_string($value)) {
$index++;
$formattedArray[$index]['title'] = $value;
$formattedArray[$index]['units'] = [];
// The rest of the code in "foreach scope" is for integer values, so skip the remaining part
continue;
}
// If the following line is executing, the value is an integer
// Push the value to the current item's units
$formattedArray[$index]['units'][] = $value;
}
var_dump($formattedArray);
$originalArray = ['a', 1, 2, 3, 'b', 4, 5, 6];
function formatArray($input) {
$output = [];
foreach($input as $inputRow) {
if (is_string($inputRow)) {
$output[] = ['title' => $inputRow, 'units' => []];
} elseif (count($output)) {
$output[count($output)-1]['units'][] = $inputRow;
}
}
return $output;
}
var_dump(formatArray($originalArray));
Note that your numbers after the title CANNOT be strings, otherwise this function will recognize it as new titles.
This code will output:
array(2) {
[0]=>
array(2) {
["title"]=>
string(1) "a"
["units"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
[1]=>
array(2) {
["title"]=>
string(1) "b"
["units"]=>
array(3) {
[0]=>
int(4)
[1]=>
int(5)
[2]=>
int(6)
}
}
}
Approach: loop over values in array, check for value if its converted to int is equal to 0, So group by that key, otherwise accumelate they next elements.
<?php
$unitsList = [ "Aulas Gratuitas", "149", "151", "153", "Módulo 0", "964", "989", "Módulo 1", "985", "1079", "1001", "1003", "Módulo 2", "1009" ];
$result = [];
foreach ($unitsList as $key => $value) {
if(intval($value)==0){
$result[] = ['title' => $value, 'units' => []];
}else{
$result[count($result)-1]['units'][] = $value;
}
}
print_r(array_values($result));
?>
I've just come across a problem, which apparently looks simple, but I can't find a solution. I have the following array in PHP:
[
"name" => "user"
0 => "created_at"
"email" => "mail"
]
And I need to get an array like this:
[
"name"
"created_at"
"email"
]
As you can see, I only need to obtain the original keys from the array, but in case a value from the original array does not have an associated value, then return the value instead of the key.
I have tried several ways using the following methods:
array_flip()
array_keys()
array_values()
I would appreciate in advance anyone who could help me.
Loop through the array and add the desired values to your new array:
$a = [
"name" => "user",
0 => "created_at",
"email" => "mail",
];
$b = [];
foreach ( $a as $k => $v ) {
$b[] = ( $k ? $k : $v );
}
print_r($b);
/*
Array
(
[0] => name
[1] => created_at
[2] => email
)
*/
For a more sophisticated determination of which key(s) to keep, replace the first $k in the ternary expression with a function that tests $k for validity:
$b[] = ( test($k) ? $k : $v );
// ...
function test($k) {
return ! is_number($k); // For example
}
is just a simple foreach
<?php
$test=
[
"name" => "user"
,0 => "created_at"
,"email" => "mail"
];
$res=[];
foreach(array_keys($test) as $ch){
(is_numeric($ch) and ($res[]=$test[$ch]) )or ($res[]=$ch);
}
var_dump($res);
?>
I have an array like this:
$arr = ({
"ID":"10",
"date":"04\/22\/20"
},
{
"ID":"20",
"date":"05\/25\/20"
},
{
"ID":"32",
"date":"07\/13\/20"
});
I want to know if values on 2 different keys exist in the array, how can I Achieve that?
Example: if id is equal to 32 and date equals to 07/13/20, return true.
I've tried in_array($monthName, array_column($GLOBALS['group_posts_array'], 'month')); but this only works on one key. I want to achieve to keys at once, kind of like && in if statement.
I don't think $arr in the question is a valid php array, but if it should be a multidimensional array, you might also pass for example an array to in_array with the keys and values that you are looking for:
$arr = [
[
"ID" => "10",
"date" => "04\/22\/20"
],
[
"ID" => "20",
"date" => "05\/25\/20"
],
[
"ID" => "32",
"date" => "07\/13\/20"
]
];
$values = [
"ID" => "32",
"date" => "07\/13\/20"
];
var_dump(in_array($values, $arr, true));
$values["ID"] = "33";
var_dump(in_array($values, $arr, true));
Output
bool(true)
bool(false)
You can implement a 'some' function.
function some(array $arr, callable $fn):bool{
foreach($arr as $index=>$item){
if($fn($item, $index)){
return true;
}
}
return false;
}
The usage would be something like the following:
$id = 32;
$date = "07/13/20";
$isInArray = some($arr, function($item, $index) use ($id, $date){
return $item->id == $id && $item->date == $date;
})
I made a search but no success. I always get some error...
What I want is, get the average of the values "Import" grouped by date.
I appreciate if someone can help me...
My JSON file:
[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]
My PHP Script:
$url = dirname(__DIR__ ) . '/admin/json/all.json';
$json = file_get_contents($url);
$array_origin = json_decode($json, TRUE);
$stack=array();
foreach ($array_origin as $v) {
$stack[$v['Date']]['Import'] = isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import'] : $v['Import'];
$stack[$v['Date']]['Export'] = isset($v['Date']) ? $stack[$v['Date']]['Export'] + $v['Export'] : $v['Export'];
$stack[$v['Date']]['Average_Import'] = 'GET HERE AVERAGE';
}
echo '<pre>' . var_export($stack, true) . '</pre>';
Thanks in advance.
Cheers
What I want is, get the average of the values "Import"
Simple
$array_origin = json_decode('[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]', true);
echo round(array_sum(array_column($array_origin, 'Import'))/count($array_origin));
Output
367
Sandbox
This is an aggregate value of all the rows, so it doesn't make much sense to store it in each of the rows.
If not all rows have the Import you can just make the column a variable and count that instead:
$import = array_column($array_origin, 'Import'); //["200","800","100"]
echo round(array_sum($import)/count($import));
UPDATE
While this wasn't clear
No, because as you see, have a filter "by date". You are printing all itens, not by date. :( –
It's still a trivial problem (once you know how many items there are and the total).
$stack = [];
foreach ($array_origin as $v) {
$key = $v['Date'];
if(!isset($stack[$key])) $stack[$key] = [];
$stack[$key]['Import'] = isset($stack[$key]['Import']) ? $stack[$key]['Import'] + $v['Import'] : $v['Import'];
$stack[$key]['Export'] = isset($stack[$key]['Export']) ? $stack[$key]['Export'] + $v['Export'] : $v['Export'];
//track the number of items
$stack[$key]['items'] = isset($stack[$key]['items'] ) ? ++$stack[$key]['items'] : 1;
$stack[$key]['Average_Import'] = 'GET HERE AVERAGE';
}
//cant average tell you know what they are, this will have to be done after the foreach
array_walk($stack,function(&$item){
$item['Average_Import'] = $item['Export']/$item['items'];
return $item;
});
print_r ($stack);
Output
Array
(
[2019-03] => Array
(
[Import] => 1000
[Export] => 250
[items] => 2
[Average_Import] => 125
)
[2019-04] => Array
(
[Import] => 100
[Export] => 600
[items] => 1
[Average_Import] => 600
)
)
Additionally, this foreach loop was just littered with issues, so I fixed them up. Mostly little things...
For example:
isset($v['Date']) ? $stack[$v['Date']]['Import'] + $v['Import']
This does nothing to prevent read errors from addition, for this value ['Import']. This isset($v['Date']) can be true all day long and that tells us nothing about if $stack[$v['Date']]['Import'] is set or not. If it's not set and we try to read it for addition (have to know its value to add to it) we will get a notice for undefined index.
Sandbox
Now If you don't want to track those item counts ( for whatever reason )
This is a nice trick (plus its fun) to get the number of items for a given date:
$num_dates = array_count_values(array_column($array_origin, 'Date'));
Output
Array
(
[2019-03] => 2
[2019-04] => 1
)
That will give you that information, Then use $num_dates in the callback (literally, pun intended) and the key of the item:
foreach ($array_origin as $v) {
$key = $v['Date'];
if(!isset($stack[$key])) $stack[$key] = [];
$stack[$key]['Import'] = isset($stack[$key]['Import']) ? $stack[$key]['Import'] + $v['Import'] : $v['Import'];
$stack[$key]['Export'] = isset($stack[$key]['Export']) ? $stack[$key]['Export'] + $v['Export'] : $v['Export'];
$stack[$key]['Average_Import'] = 'GET HERE AVERAGE';
}
$num_dates = array_count_values(array_column($array_origin, 'Date'));
array_walk($stack,function(&$item,$key)use($num_dates){
//may want to check if $key exists (but it should always)
$item['Average_Import'] = $item['Export']/$num_dates[$key];
return $item;
});
Output
Array
(
[2019-03] => Array
(
[Import] => 1000
[Export] => 250
[Average_Import] => 125
)
[2019-04] => Array
(
[Import] => 100
[Export] => 600
[Average_Import] => 600
)
)
Sandbox
$array_origin = json_decode('[
{
"Date": "2019-03",
"Import": "200",
"Export": "50"
},
{
"Date": "2019-03",
"Import": "800",
"Export": "200"
},
{
"Date": "2019-04",
"Import": "100",
"Export": "600"
}
]', true);
$counts = [];
$imports = [];
foreach ($array_origin as $data) {
if (isset($data['Import']) && isset($data['Date'])) {
if (!isset($counts[$data['Date']])) {
$counts[$data['Date']] = 0;
$imports[$data['Date']] = 0;
}
$counts[$data['Date']]++;
$imports[$data['Date']] = intval($data['Import']) + $imports[$data['Date']];
}
}
$importAverage = [];
foreach ($imports as $date => $importSum) {
$importAverage[$date] = $importSum > 0 ? $importSum / $counts[$date] : 0;
}
var_dump($importAverage);
array (size=2)
'2019-03' => int 500
'2019-04' => int 100
While plucking from a database, I get id as strings.
$alphabets = new Alphabet();
return $alphabets->pluck('name', 'id');
Output
{
"1": "Apple",
"2": "Ball",
"3": "Cat"
}
Expected
{
1: "Apple",
2: "Ball",
3: "Cat"
}
But, when I reverse ID and name,
return $alphabets->pluck('id', 'name');
I get id as integer.
{
"Apple": 1,
"Ball": 2,
"Cat": 3
}
I'm not sure what's happening behind the scene. But how can I get ID in integer ? Actually, old flash session doesn't set value because of 1 vs "1" in Form Collective.
{!! Form::select('alphabet', $alphabets, null, ['class' => 'form-control', 'multiple' => true]) !!}
Try this code
$alphabets = new Alphabet();
return $alphabets->all()->pluck('name', 'id');
Alphabet.php
You should cast your columns like this.
protected $casts = [
'id' => 'integer',
'name' => 'string'
];
I think I found the answer here.
https://laracasts.com/discuss/channels/laravel/pluck-id-integer-cast-to-string
Here I found JSON only allows key names to be strings.
Using number as "index" (JSON)
{
"1": "Apple",
"2": "Ball",
"3": "Cat"
}
Actually, I want to achieve it for Form Collective. It was a bug and it's PR has been merged now.
https://github.com/LaravelCollective/html/pull/368#pullrequestreview-46820423
you also convert key into int
$alphabets = new Alphabet();
$alphaArr =$alphabets->pluck('name', 'id');
foreach($array as $key => $value) {
$newArray[(int) $key] = $value;
}
Usually, pluck() method gives you associative array of values
in string values.
So, try using select statements like this:
$data = Alphabet::select('id','name')->get()->toArray();
This will give you following result:
array:3 [▼
0 => array:2 [▼
"id" => 1
"name" => "Apple"
]
1 => array:2 [▼
"id" => 2
"name" => "Ball"
]
2 => array:2 [▼
"id" => 3
"name" => "Cat"
]
]
Now, using simple loop you can get your expected array.
$expected = array();
foreach($data as $d){
$expected[$d['name']] = $d['id'];
}
dd($expected);
Adding this line fix the old session issue of LaravelCollective/Html.
|| in_array((string) $value, $selected, true)
/**
* Determine if the value is selected.
*
* #param string $value
* #param string $selected
*
* #return null|string
*/
protected function getSelectedValue($value, $selected)
{
if (is_array($selected)) {
return in_array($value, $selected, true) || in_array((string) $value, $selected, true) ? 'selected' : null;
} elseif ($selected instanceof Collection) {
return $selected->contains($value) ? 'selected' : null;
}
return ((string) $value == (string) $selected) ? 'selected' : null;
}