How to count numbers of keys in an array of objects [duplicate] - php

This question already has answers here:
php - Is it possible to count the number of keys in an array?
(4 answers)
Closed 6 years ago.
I am using laravel 5, I need count the keys available inside every array index suppose for array[0] it has 7 keys, now I need the last key and before last key to compare which's value is bigger. how I can do using loop,as far I have tried.
Please Note The inner keys are stored as object key=>value pair.
foreach ($regions as $regions_key => $regions_value) {
echo sizeof($regions_key)
}
Help is appreciated.

Wouldn't you just count it within your loop:
$total = 0;
foreach($data as $sub_array) {
$total += count($sub_array);
}
After the above iteration is done to find your counts, $total will hold your count.
Example/Demo

Try this:
$countArr = array();
foreach ($regions as $regions_key => $regions_value) {
$countArr[$regions_key] = count($regions[$regions_key]); // create array of length of sub array
}
echo max($countArr); // max — Find highest value

To count the number of keys in an array. Try
$arr = Array
(
0 => 'hello',
1 => 'there',
2 => null,
3 => null,
4 => 3,
);
var_dump(count($arr));

Related

Breaking array loop in 2 parts each [duplicate]

This question already has answers here:
Process every two elements in a flat array
(4 answers)
Closed 6 days ago.
I have an array loop 1st value in array is name and second value is the value to be inserted in the combination of 2 the array printing like this
Array
(
[0] => LE781291334
[1] => 0
[2] => JR792682920
[3] => 8,000.00
[4] => JR792733067
[5] => 1,800.00
[6] => JR792733072
[7] => 1,500.00
[8] => JR792733069
[9] => 700
[10] => JR792733068
)
Which I need every array values to be paired so I can add them into database like this
INSERT INTO table_name (valname, value) VALUES ('LE781291334', 0)
INSERT INTO table_name (valname, value) VALUES ('JR792682920', 8,000.00)
INSERT INTO table_name (valname, value) VALUES ('JR792733067', 1,800.00)
I am totally confused the value coming through api and I cannot pair them can anyone help me out for adding them in paired way?
It seems you need to array_chunk the array.
The function array_chunk will chunk up an array in x parts with $n number of items in each.
$n = 2;
$result = array_chunk($yourarray, $n);
Use it then like:
foreach($result as $sub){
list($valname, $val) = $sub;
// Your table code
}
$newarray = array();
for ($i = 0; $i < count($yourarray) / 2; $i++) {
$newarray[$yourarray[$i*2]] = $yourarray[$i * 2 + 1];
}
This assumes $yourarray is an indexed array with an even number of elements, so each key is paired to the succeeding value.
array_chunk as in the previous answer seems to accomplish the same thing, this is just a simple loop to show how it might work.
You could then insert into database with something like this:
foreach ($newarray as $x => $x_value) {
// sql to insert here - $x is the key and $x_value is the value
}

PHP array sort with forced the first row [duplicate]

This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)

Convert array of values to nested associative array [duplicate]

This question already has answers here:
php create multidimensional array from flat one
(4 answers)
Closed 4 years ago.
php create multidimensional array from flat one
Tried this but counting backwards won't work as I need to move from start to finish in the order in which the array is originally.
I have a simple array:
0 => Item #1
1 => Item #2
2 => Item #3
I need to create an associative array from the above like so:
Item #1
=> Item #2
=> Item #3
Where each value becomes the key for the parent item. This must be done in a while loop not recursion. It MUST move forward, the loop performs a look-ahead for validation purposes, so the original order is imperative
Thanks
EDIT - this is giving me the intended result I just can't get my around how to do this in the main loop |
array:3 [
0 => "workorder"
1 => "company"
2 => "name"
]
$array['workorder'] = [];
$temp = &$array['workorder'];
$temp['company'] = [];
$temp2 = &$temp['company'];
$temp2['name'] = [];
dump($array);
exit;
EDIT 2 | Main loop
$type = current($types);
while (array_key_exists($type, $this->types)) {
$nextType = next($types);
// ... do stuff
$type = $nextType;
}
return $array;
Try
// This array contain the keys for associative array
$arrayKeys = ['name1', 'name2', 'name3'];
// This array contain the values for associative array
$arrayItems = ['item1', 'item2', 'item3'];
// this array will be the associative array
$newArray = [];
$count = count($arrayKeys) -1;
while( $count >= 0 ){
$newArray[ $arrayKeys[$count] ] = $arrayItems[$count];
echo '<Br>';
$count--;
}

getting the smallest value php [duplicate]

This question already has an answer here:
Find which int was minimum in PHP [closed]
(1 answer)
Closed 9 years ago.
I am trying to retrieve the smallest value from an array. Here is my code:
$postID = get_the_id();
$variationP = get_post_meta($postID, '_variations', TRUE);
print_r($variationP);
This outputs the following:
Array ( [0] => 1 [1] => 2 [2] => 3 )
I am then looping through the array like this:
foreach ($variationP as $price){
echo $price;
}
Which then outputs the results like this:
123
How do I go about returning only the smallest result? I need just 1 to be returned.
Just echo array: min() returns the numerically lowest of the parameter values or array.
echo min($variationP);
If you want algorithm (not using min), it's really easy:
$min = 0;
function minPrice($elements){
foreach ($elements as $price){
if($min > $price){
$min = $price;
}
}
return $min;
}
It's good solution when you compare more complex elements, for example models from orm.
Use PHP's min() function:
$array = Array ( [0] => 1 [1] => 2 [2] => 3 );
$minimum = min($array);
echo $minimum; // 1
You can use min() function to get the smallest number in an array.
$a = array(3, 1, 2);
echo min($a);
This code output:
1
use min() function to get minimum value.

PHP Sort Array based on values in another [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP - sort an array based on another array?
Need some help regarding array sorting....
I have two arrays. The main one (where the key is the user id) :
$user[31] = 'Tom'
$user[43] = 'Jane'
and another array with the order they should be displayed (where key is the order and value is the user id) :
$order[1] = 43
$order[2] = 31
How can I apply the ordering to the main array using the ordering one?
Thanks guys!
Use the keys in $order to select the users from $user in the right order:
$orderedUsers = array();
foreach ($order as $key) {
$orderedUsers[] = $user[$key];
}
Use this one, it is usefull for your problem
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
Result as :
Array
(
[0] => XL
[1] => gold
)

Categories