How can I custom multidimensional array? - php

I have array like this :
$a = array('value' =>
array(
'lesson_id' => array('1','6'),
'knowledge_value' => array('2','7'),
'knowledge_description' => array('3','8'),
'skill_value' => array('4','9'),
'skill_description' => array('5','10')
)
);
I want to change it to be like this :
$a = array('value' =>
array(
array(
'lesson_id' => '1',
'knowledge_value' => '2',
'knowledge_description' => '3',
'skill_value' => '4',
'skill_description' => '5'
),
array(
'lesson_id' => '6',
'knowledge_value' => '7',
'knowledge_description' => '8',
'skill_value' => '9',
'skill_description' => '10'
),
)
);
How can I do it?

Demo Link
Here is the snippet for you to work, please see inline doc for explanation
$temp = [];
$keys = array_keys($a['value']); // fetched all keys
for ($i = 0; $i < count($a['value']['lesson_id']); $i++) { // compared with first count of lession_id
$temp['value'][] = array_combine($keys, array_column($a['value'], $i)); // combined key and values
}
array_keys ā€” Return all the keys or a subset of the keys of an array
array_combine ā€” Creates an array by using one array for keys and another for its values
array_column ā€” Return the values from a single column in the input array

Related

Offset by number in an array

I just can't figure it out, there is a code like this:
$a1 = ['k1' => '1', 'k2' => '2','k3' => '3', 'k4' => '4', 'k5' => '5'];
$a2 = ['k1' => '-1', 'k2' => '-2','k3' => '-3', 'k4' => '-4', 'k5' => '-5'];
$ix = 1; // number to move to
$k = 'k3'; // the key we want to move
$i = 1; // iteration number
$oldk1 = $oldk2 = '';
foreach($a1 as $key => $value) {
if($k === $key && $ix != $i) {
$oldk1 = $value;
$oldk2 = $a2[$k];
unset($a1[$k], $a2[$k]);
}
if($i === $ix) {
$a1[$k] = $oldk1;
$a2[$k] = $oldk2;
}
++$i;
}
But it does not work, why I cannot understand what I was trying to do, I cannot solve this problem.
It consists in the following:
2 arrays with the same keys, but with different values, they must always go through the keys in the same order.
How to make it so that when I want, for example, that k3 stands in 1 place or on any other, I enter a number from 1 to the maximum in the array and so that in 2 arrays it is rearranged to the specified number and so that it is already like this:
$a1 = ['k3' => '3', 'k1' => '1', 'k2' => '2', 'k4' => '4', 'k5' => '5'];
$a2 = ['k3' => '-3', 'k1' => '-1', 'k2' => '-2', 'k4' => '-4', 'k5' => '-5'];
Moving an array element by key to a new position. Here the index of the first element in the array starts at 1 as described in the question.
$a1 = ['k1' => '1', 'k2' => '2','k3' => '3', 'k4' => '4', 'k5' => '5'];
$a2 = ['k1' => '-1', 'k2' => '-2','k3' => '-3', 'k4' => '-4', 'k5' => '-5'];
$k = 'k3'; // Key to move
$i = 1; // New position index
// Retrieve the element with key $k
$element = array_splice($a1, array_flip(array_keys($a1))[$k], 1);
// Insert an element at a new position
$a1 = array_merge(
array_slice($a1, 0, $i - 1),
$element,
array_slice($a1, $i - 1)
);
// Rearrange $a2 keys and values by $a1 array
$a2 = array_merge($a1, $a2);
print_r($a1);
print_r($a2);

Get the max value

I'm pretty new to PHP and i'm stuck in the following scenario. I have an array with some values and I want to get the max value in the array set.
For ex:
$array = array(
0 => array(
'1' => '123',
'2' => '120',
'3' => '30',
'4' => '150'
),
1 => array(
'1' => '123',
'2' => '122',
'3' => '30',
'4' => '158'
),
2 => array(
'1' => '123',
'2' => '129',
'3' => '300',
'4' => '150'
)
);
The value i'm expecting is 300.
I have tried the following code and i don't know how to get the maximum value from all the sub arrays.
$max = 0;
foreach( $array as $k => $v ){
//this is where i need help
}
Any kind of help would be highly appreciated.
You can flatten your array first using array_merge(...$array), then just use the max() function:
$new_array = array_merge(...$array);
echo max($new_array);
Demo
I took #Hirumina's solution and just set $max = $y if $y was > $max
$max = 0;
foreach( $array as $k => $v ) {
foreach($v as $x => $y) {
if($y > $max){
$max = $y;
}
}
}
echo $max;
$new_array = array_map(function($value){
return max($value);
}, $array);
echo max($new_array);
Here array_map function will get max value from individual $array and store in $new_array.
Then max($new_array) will give you max value.

Check if the value of a key in one array is equal to the value of different key in another array

I have 2 multidimensional arrays and I want to get the 1st array where the value of [file] key in array 1 is equal to value of [folder_name] key in array 2
$arr1 = [
[
'is_dir' => '1',
'file' => 'hello member',
'file_lcase' => 'hello member',
'date' => '1550733362',
'size' => '0',
'permissions' => '',
'extension' => 'dir',
],
[
'is_dir' => '1',
'file' => 'in in test',
'file_lcase' => 'in in test',
'date' => '1550730845',
'size' => '0',
'permissions' => '',
'extension' => 'dir',
]
];
$arr2 = [
[
'dic_id' => '64',
'folder_name' => 'hello member',
'share_with' => '11',
],
[
'dic_id' => '65',
'folder_name' => 'hello inside',
'share_with' => '11',
],
[
'dic_id' => '66',
'folder_name' => 'in in test',
'share_with' => '11',
],
];
I have tried while looping 2 arrays and getting to one array but it is not success.
We can iterate both arrays inside each other to check until we have a match.
Please be aware that this shows only the first match. If you want to keep all matches you should use another helper array to store first array values that matches to second array.
foreach ($array1 as $key => $value) {
foreach ($array2 as $id => $item) {
if($value['file'] == $item['folder_name']){
// we have a match so we print out the first array element
print_r($array1[$key]);
break;
}
}
}
To avoid a double loop that gives a time complexity of O(nĀ²), you could first create the set of "folder_name" values (as keys), and then use that to filter the first array. Both these operations have a time complexity of O(n) which is certainly more efficient for larger arrays:
$result = [];
$set = array_flip(array_column($arr2, "folder_name"));
foreach ($arr1 as $elem) {
if (isset($set[$elem["file"]])) $result[] = $elem;
}
$result will have the elements of $arr1 that meet the requirement.
$arr1 = array();
$arr2 = array();
$arr3 = array();
$arr1[] = array('is_dir'=>'1','file'=>'hello member','file_lcase'=>'hello member','date'=>'1550733362','size'=>'0','permissions'=>'','extension'=>'dir');
$arr1[] = array('is_dir'=>'1','file'=>'in in test','file_lcase'=>'in in test','date'=>'1550730845','size'=>'0','permissions'=>'','extension'=>'dir');
$arr2[] = array('dic_id'=>'64','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'65','folder_name'=>'hello member','share_with'=>'11');
$arr2[] = array('dic_id'=>'66','folder_name'=>'in in test','share_with'=>'11');
foreach($arr1 as $a){
foreach($arr2 as $a2){
if($a['file'] == $a2['folder_name']){
$arr3[]=$a;
}
}
}
$arr3 = array_map("unserialize", array_unique(array_map("serialize", $arr3))); // remove duplicates
var_dump($arr3);
$arr3 contains the resultant array.

Alter array rows to be associative and append an additional associative element

I've created a method that allows me to assign keys to rows of values, and appends extra keys and values.
It adds all the new keys to a keys array, then adds all new values to the values array, and then combines all the keys and values.
How can I shrink it to make it smaller and more efficient?
$valores = array(array("1","1","1","1"),array("2","2","2","2"));//array of values
$keys = array('k1','k2','k3','k4'); //array of keys
$id = array('SpecialKey' => 'SpecialValue');//new array of items I want to add
function formatarArray($arrValores,$arrKeys,$identificadores){
foreach($identificadores as $k => $v){
array_push($arrKeys, $k);
}
foreach($arrValores as $i => $arrValor)
{
foreach($identificadores as $k => $v){
array_push($arrValor, $v);
}
$arrValores[$i] = array_combine($arrKeys, $arrValor);
}
var_export($arrValores);
}
Output:
array (
0 =>
array (
'k1' => '1',
'k2' => '1',
'k3' => '1',
'k4' => '1',
'SpecialKey' => 'SpecialValue',
),
1 =>
array (
'k1' => '2',
'k2' => '2',
'k3' => '2',
'k4' => '2',
'SpecialKey' => 'SpecialValue',
),
)
Viper-7(code debug):
http://viper-7.com/hbE1YF
function formatarArray($arrValores, $arrKeys, $identificadores)
{
foreach ($arrValores as &$arr)
$arr = array_merge(array_combine($arrKeys, $arr), $identificadores);
print_r($arrValores);
}
Could even be done in one line...
function formatarArray($arrValores, $arrKeys, $identificadores)
{
print_r(array_map(function ($arr) use ($arrKeys, $identificadores) { return array_merge(array_combine($arrKeys, $arr), $identificadores); }, $arrValores));
}
As a modernized form of #havenard's answer, I'd use PHP7.4's arrow function syntax to avoid the need for use() and I would use the array union operator (+) to avoid the iterated array_merge() calls. The array union operator is appropriate because it is adding an associative array to another array.
Code: (Demo)
var_export(
array_map(
fn($row) => array_combine($keys, $row) + $id,
$valores
)
);

Throw away whole array but the first item

Assume I have the following array:
$array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
)
I am only interested in the first $array item:
$array2 = array('key'=> 32, 'name' => 'paul', 'age' => 43)
What is the most efficient way to accomplish this? In other words, can I throw out all other items of $array with one command?
Use array_shift().
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be touched.
$array2 = array_shift($array);
This means that $array2 now holds the first element, while $array holds the rest of the elements.
try this
$array2 = array_shift($array);
$newArr = reset($array);
I think there is no problem with that.
There are 2 options, really. Either you can just select the first item in the array
$array2 = $array[0];
Or you could use array_slice as
$array2 = array_slice($array, 0, 1);
Array_shift is probably the best way. But just for fun here is another way.
$first_element = end(array_reverse($array));
$k = array_merge(array('key' => key($array)), array_shift($array));
Returns in the specified format.
key gets you the first key, array_shift gets you the first value, and merge using array_merge
resetting an array also returns the first element (end() returns the last):
$first = reset( $array );
http://www.php.net/manual/en/function.reset.php
But to generate the exact result you want, you could write something like this
foreach( $array as $k => $first ){ // get first sub-array and its key
$first['key'] = $k; // add the key
break; // we don't care about the other elements, goodbye
}
Futuregeek's method fixed:
$first =
// returns first element, and sets it as the current element for key()
reset( $array )
// instead of array_merge, (sometimes) you can use the + operator
+
// key() will return the appropriate key after reset()
array('key' => key( $array ));
Try It :
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
foreach($arr as $key => $value)
{
$result[$key] = $value;
break;
}
print_r($result);
##-------Secount Way If you don't want Key 32--------------------------
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$arr = array_reverse($arr);
print_r(end($arr));
#------ Third Way If you don't want Key 32 -------------
echo "<br>=======<br>";
$arr = array(
'32' => array('name' => 'paul', 'age' => 43),
'17' => array('name' => 'eric', 'age' => 19),
'99' => array('name' => 'dave', 'age' => 65)
);
$array2 = array_shift($arr);
print_r($array2);

Categories