Problem with a specific task using associative arrays in PHP - php

I've been stuck on this for the better part of the day and I'm out of ideas. I have an array like this:
Array
(
[rank] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[name] => Array
(
[0] => 'Hideki'
[1] => 'Rory'
[2] => 'Sam'
[money] => Array
(
[0] => '$100'
[1] => '$200'
[2] => '$500'
)
)
and I have the task to create an array with the following format from it:
Array
(
[Hideki] => Array
(
[rank] => 1
[money] => '$100'
)
[Rory] => Array
(
[rank] => 2
[money] => '$200'
[Sam] => Array
(
[rank] => 3
[money] => '$500'
)
)
The catch is that 'rank' and 'money' have to be dynamic names

It should be simple as that:
$new = [];
foreach($array['name'] as $key => $name) {
$new[$name] = [
'rank' => $array['rank'][$key],
'money' => $array['money'][$key]
];
}

Little late but here my answear. My approach was to use the array_walk() function.
$array = [
'rank' => [1,2,3],
'name' => ['Hideki', 'Rory', 'Sam'],
'money' => ['$100', '$200', '$500'],
];
$i = 0;
$newArray = [];
array_walk($array['name'], function($name) use (&$i, $array, &$newArray) {
$newArray[$name] = ['rank'=> $array['rank'][$i], 'money' => $array['money'][$i]];
$i++;
});
print_r($newArray);

Run your first array through a foreach loop referencing only the "name" key and using key=>value pairs. Then reference the other keys from the first array when you build the new array, setting the value as the key to the second array.
You will need to first get the keys using array_keys() and use a nested foreach to loop through all the keys.
Example:
$keys1 = array_keys($array1);
foreach ($array1['name'] as $key => $value) {
$val2 = array();
foreach ($keys1 as $k){
if ($k != 'name') $val2[$k] = $array1[$k][$key];
}
$array2[$value] = $val2;
}

Related

Insert an array into another array on same values

I have this array:
ARRAY 1
Array
(
[0] => Array
(
[required] => Tip:
)
[1] => Array
(
[required] => Flux:
)
[2] => Array
)
ARRAY 2
Array
(
[0] => Array
(
[name] => Flux:
)
[1] => Array
(
[name] => Tip:
)
[2] => Array
(
[name] => Weight:
)
)
How insert data from array 1 to array 2 when value of name and required are same.
Data from array some time don't have same values of name and required.
On output of array 2 I want to display something when value of required exist.
I need this:
Array
(
[0] => Array
(
[name] => Flux:
[required] => Flux:
)
[1] => Array
(
[name] => Tip:
[required] => Tip:
)
[2] => Array
(
[name] => Weight:
[required] =>
)
)
I tried with this:
foreach($char as $key =>$value){
foreach($mandatory as $key =>$val){
$data[] = array("name" => $value->charact_name, "required" => $val);
}
}
But is not output what I expect! It show me diferent values on name and required
This question is not a technical problem and you needed a little more tries to achieve a true algorithm.
I did some modifications to your code. $key variable must be different for two foreachs. Based on your question new key required just added to $arr2.
$arr1 = [['required' => 'Tip:'], ['required' => 'Flux:']];
$arr2 = [['name' => 'Flux:'], ['name' => 'Tip:'], ['name' => 'Weight:']];
foreach($arr2 as $key2 => $value2) {
$arr2[$key2]['required'] = NULL;
foreach($arr1 as $value1)
if($value2['name'] == $value1['required']) {
$arr2[$key2]['required'] = $value1['required'];
break;
}
}
I tried this:
foreach($char as $key2 => $value2) {
foreach($mandatory as $value1)
if($value2->charact_name == $value1) {
$data[] = array("name" => $value2->charact_name, "required" => $value1);
}
}
But data array it show me name and required only for values that is in $mandatory array, I want to display all from $char and when value exist in $mandatory add [required]=> name of value from $mandatory
You can simply create it with nested loops which cause time complexity O(n*m). However if you use a Hashmap (array with key value) which get O(1) to search you can create it very fast by O(n+m) as below:
<?php
$arr1 = array(0 => array('name' => 'Flux'),1 => array('name' => 'Tip'),2 => array('name' => 'Weight'));
$arr2 = array(0 => array('required' => 'Tip'),1 => array('required' => 'Flux'),2 => array());
$arrkey = array();
foreach ($arr1 as $ix=>$value) {
$arrkey[$value['name']]=$ix;
}
$arr3 = $arr1;
foreach ($arr2 as $elem) {
if(!empty($elem) && array_key_exists($elem['required'],$arrkey)) {
$arr3[$arrkey[$elem['required']]]['required'] = $elem['required'];
}
}
print_r($arr3);
?>
Try this online demo.

How to loop multi dimensional array to get values

I have this multi-dimensional array and I'm trying to convert it into array given below
Array
(
[id] => Array
(
[0] => 1
[1] => 3
)
[team_id] => Array
(
[0] => 654868479
[1] => 463733228
)
[seed] => Array
(
[0] => 1
[1] => 2
)
)
I want following result
Array
(
[0] => Array
(
[id] => 1
[team_id] => 654868479
[seed] => 1
)
[1] => Array
(
[id] => 3
[team_id] => 463733228
[seed] => 3
)
)
Here is what I have achieved so far. I actually want $seeded[] array is the same format as it is required to submit update_batch. Which will ultimately update database records.
$seeds = $this->input->post();
$i=0;
foreach ($seeds as $key => $value){
if(!empty($key) && !empty($value)){
for($i=0; $i=5; $i++) {
$seeded[] = array(
'id' => (id go here),
'tournament_id' => $tournament_id,
'stage_id' => $stage_id,
'seed_id' => (seed go here),
'team_name' => (team_id go here),
);
}
$this->db->update_batch('tournament_seed', $seeded, 'id');
}
}
Iterate the array and convert it using below code.
$seeded= array();
for($i =0; $i < count($seeds['id']); $i++){
$tempArr['id'] = $seeds['id'][$i];
$tempArr['team_id'] = $seeds['team_id'][$i];
$tempArr['seed'] = $seeds['seed'][$i];
$seeded[] = $tempArr;
}
I've written a function that will allow you to transform any array of similar structure to what you have above, to an array of the form you are looking for.
You can build your array in this way:
$arr = [
'id' => [1, 3],
'team_id' => [654868479, 463733228],
'seed' => [1, 2],
];
function array_flatten($arr) {
$res = [];
foreach($arr as $id => $valuesArray) {
foreach($valuesArray as $index => $value)
$res[$index][$id] = $value;
}
return $res;
}
print_r(array_flatten($arr));
Hope this helps,

Array inside array or nested array

I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it

Splice an array when key_value same?

My sorted array needs to be split up so that each created array has all of those associated with that value.
Array (
[NAME] => Array
(
[0] => Fooaz
[1] => bzdsfdasfz
[2] => Fooooooooo
)
[DESCRIPTION] => Array
(
[0] => Foo
[1] => Foo
[2] => Barrrr
)
)
For example, from that array I want to get two arrays. One containing:
[NAME]=>Array([0] => Fooooooooo), [DESCRIPTION]=>Array([0] => Barrrr):
The other containing the remaining elements.
What's an efficient way of doing this?
$arr = Array (
'NAME' => Array
(
0 => 'Fooaz',
1 => 'bzdsfdasfz',
2 => 'Fooooooooo'
),
'DESCRIPTION' => Array
(
0 => 'Foo',
1 => 'Foo',
2 => 'Barrrr'
)
);
$arr1 = array();
foreach ($arr as $key => $value) {
$arr1[$key][] = array_pop($arr[$key]);
}
print_r($arr);
print_r($arr1);
Use array_pop():
http://codepad.org/GeP6OEtf
<?php
$arr=array(
"NAME"=>array('a','b','c','d'),
"DESC"=>array('A','B','C','D')
);
$newarr=array();
foreach ($arr as $key=>$value) {
$newarr[$key]=array(array_pop($arr[$key]));
}
print_r($arr);
echo "\n-------------\n";
print_r($newarr);
You can use extract function.
extract($array);
this will give you two arrays automatically.
reference

Build associative array based on values of another associative array

I'm looking for an elegant way to turn this array:
Array (
[foo] => 1
[bar] => 1
[zim] => 3
[dib] => 6
[gir] => 1
[gaz] => 3
)
Into this array:
Array (
[1] => Array ( foo, bar, gir ),
[3] => Array ( zim, gaz ),
[6] => Array ( dib )
)
Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.
Thanks!
$input = array(
'foo' => 1,
'bar' => 1,
'zim' => 3,
'dib' => 6,
'gir' => 1,
'gaz' => 3
)
$output = array();
foreach ( $input as $k => $v ) {
if ( !isset($output[$v]) ) {
$output[$v] = array();
}
$output[$v][] = $k;
}
I think this will do it just fine:
foreach ($arr1 as $k => $val) $arr2[$val][] = $k;
where $arr1 is the original array outputting the new array to $arr2.

Categories