Which PHP Array function should I use? - php

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc

Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.

foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);

I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

Related

how to get the last array with a specific key in multidimensional array

I am looking for a function to return an array and all its sub-structure for a specific criteria
Criteria:
php 5.6 compatible
Return the last instance of array with key name of !ENTITY with all
its values in-tact
Sample array:
For the multidimensional array, lets call that $arr, for this example structure it's 6 levels deep, we should not assume it's always 6 levels.
$arr = array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("!ENTITY" =>
array("svg" =>
array(
0 => array("g" => "", "#id" => "Layer_2"),
1 => array("g" => "", "#id" => "Layer_3"),
),
"#version" => 1.2,
"#id" => "Layer_1",
),
"#different" => "layer"
),
"#all" => "layer"
),
"#here" => "layer"
),
"#goes" => "layer"
),
"#else" => "layer"
),
"#something" => "layer"
);
Expected Output:
I would like to return the final array for !ENTITY with it's sub-structure all in-tact. Here is a sample of the expected output:
Array
(
[svg] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g]
[#id] => Layer_3
)
)
[#version] => 1.2
[#id] => Layer_1
)
You will need to recursively traverse the array and return resultant values if found like below:
<?php
function getLastValueForKey($data, $key){
$res = '';
foreach($data as $k => $value){
$sub_res = is_array($value) ? getLastValueForKey($value, $key) : '';
if($sub_res !== ''){
$res = $sub_res;
}else if($k === $key){
$res = $value;
}
}
return $res;
}
print_r(getLastValueForKey($arr, '!ENTITY'));
Online Demo

shift multidimentional array to single array

I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);

PHP Array of arrays of arrays

I am trying to search this array by the value of ['field'] and then return the value of ['value'] associated with that field in the array.
For example, I want to say "Tell me the value associated with theThirdField".
I've tried many, many permutations of something like the following:
$myVariable = $Array['result']['totalrows'][0]['rownum'][0]['field'];
To further clarify, I will never know which order / sub-array my search field is located in, I only know the string value associated with ['field'].
How would I accomplish this?
Array
(
[result] => Array
(
[totalrows] => 1
[rows] => Array
(
[0] => Array
(
[rownum] => 1
[values] => Array
(
[0] => Array
(
[field] => testMeOnce
[value] => 436586498
)
[1] => Array
(
[field] => testMeTwice
[value] => 327698034
)
[2] => Array
(
[field] => theThirdField
[value] => 108760374
)
[3] => Array
(
[field] => theFourthField
[value] => 2458505
)
[4] => Array
(
[field] => fifthField
[value] => -0.0201
)
)
)
)
)
)
Did you expect something like that?
$needle = 'theThirdField'; // searched field name
$valuesArray = $Array['result']['rows'][0]['values']; //now you have clearer array
array_walk($valuesArray, function($element, $key) use ($needle) {
if ($element['field'] == $needle) {
echo $element['value'];
}
});
I would do something like this, assuming you want to search only in the $myVariable dimension :
$myVariable = $Array['result']['rows'][0]['values'];
foreach ($myVariable as $key => $value) {
if( $value['field'] === 'theThirdField' ) {
echo $value['value'];
break;
}
}
when I ran your code, I got some syntax errors. I have changed your Array to this (changed syntax only):
$a = Array
(
'result' =>
[
'totalrows' => 1,
'rows' =>
[
0 =>
[
'rownum' => 1,
'values' =>
[
0 =>
[
'field' => 'testMeOnce',
'value' => 436586498
],
1 =>
[
'field' => 'testMeTwice',
'value' => 327698034
],
2 =>
[
'field' => 'theThirdField',
'value' => 108760374
],
3 =>
[
'field' => 'theFourthField',
'value' => 2458505
],
4 =>
[
'field' => 'fifthField',
'value' => -0.0201
]
]
]
]
]
);
now you can get the value like this:
print($a['result']['rows'][0]['values'][2]['value']); // --> 108760374
I hope that this is what you are looking for!
Thanks everyone. I used a mix of your suggestions and ended up doing the following:
$valuesArray = $Array['result']['rows'][0]['values'];
foreach ($valuesArray as $value) {
$fieldName = $value['field'];
$$fieldName = $value['value'];
}
Since I know the names of all the fields I want, but not the order, this allowed me to capture all of the values of each field with the name of the field becoming the variable name.

Add array elements to associative array

I am unable to find a way to take the elements of an array (product IDs) and add them to a particular key of an associative array ($choices['id]) so that it creates as many instances of that array ($choices[ ]) as there are elements in $id.
I want the final version of $choices[ ] to include as many arrays as there are elements in $id[ ].
After that I want to repeat this process for part_numbers & quantity.
// Create $choices array with keys only
$choices = array(
'id' => '',
'part_number' => '',
'quantity' => '',
);
// Insert $id array values into 'id' key of $choices[]
$id = array('181', '33', '34');
If I'm understanding your question correctly, you mean something like this?
$choices = array();
$id = array('181', '33', '34');
foreach($id as $element)
{
$choices[] = array(
'id' => $element,
'part_number' => '',
'quantity' => '',
);
}
echo "<pre>";
print_r($choices);
echo "</pre>";
Output:
Array (
[0] => Array
(
[id] => 181
[part_number] =>
[quantity] =>
)
[1] => Array
(
[id] => 33
[part_number] =>
[quantity] =>
)
[2] => Array
(
[id] => 34
[part_number] =>
[quantity] =>
)
)
Edit:
A more general solution would be as follows:
$choices = array();
$values = array('sku-123', 'sku-132', 'sku-1323');
foreach($values as $i => $value){
if(array_key_exists($i, $choices))
{
$choices[$i]['part_number'] = $value;
}
else
{
$choices[] = array(
'id' => '',
'part_number' => $value,
'quantity' => '',
);
}
}
This can be used for array creation and insertion, hence the if/else block.

PHP Replace Array Values

I have 2 multidimensional arrays that I am working with:
$arr1 =
Array
([type] => characters
[version] => 5.6.7.8
[data] => Array
([Char1] => Array
([id] => 1
[name] =>Char1
[title] =>Example
[tags] => Array
([0] => DPS
[1] => Support))
[Char2] => Array
([id] => 2
[name] =>Char2
[title] =>Example
[tags] => Array
([0] => Tank
[1] => N/A)
)
)
etc...
$arr2=
Array
([games] => Array
([gameId] => 123
[gameType => Match
[char_id] => 1
[stats] => Array
([damage] => 55555
[kills] => 5)
)
([gameId] => 157
[gameType => Match
[char_id] => 2
[stats] => Array
([damage] => 12642
[kills] => 9)
)
etc...
Basically, I need almost all the data in $arr2... but only the Char name from $arr1. How could I merge or add the $arr1['name'] key=>value into $arr2 where $arr1['id'] is equal to $arr2['char_id'] as the "id" field of each array is the same number.
I've attempted using array_merge and array_replace, but I haven't come up with any working solutions. This is also all data that I am receiving from a 3rd party, so I have no control on initial array setup.
Thanks for any help or suggestions!
Actually, this is quite straighforward. (I don't think there a built-in function that does this.)
Loop $arr2 and under it loop also $arr1. While under loop, just add a condition that if both ID's match, add that particular name to $arr2. (And use some referencing & on $arr2)
Consider this example:
// your data
$arr1 = array(
'type' => 'characters',
'version' => '5.6.7.8',
'data' => array(
'Char1' => array(
'id' => 1,
'name' => 'Char1',
'title' => 'Example',
'tags' => array('DPS', 'Support'),
),
'Char2' => array(
'id' => 2,
'name' => 'Char2',
'title' => 'Example',
'tags' => array('Tank', 'N/A'),
),
),
);
$arr2 = array(
'games' => array(
array(
'gameId' => 123,
'gameType' => 'Match',
'char_id' => 1,
'stats' => array('damage' => 55555, 'kills' => 5),
),
array(
'gameId' => 157,
'gameType' => 'Match',
'char_id' => 2,
'stats' => array('damage' => 12642, 'kills' => 9),
),
),
);
foreach($arr2['games'] as &$value) {
$arr2_char_id = $value['char_id'];
// loop and check against the $arr1
foreach($arr1['data'] as $element) {
if($arr2_char_id == $element['id']) {
$value['name'] = $element['name'];
}
}
}
echo '<pre>';
print_r($arr2);
$arr2 should look now like this:
Array
(
[games] => Array
(
[0] => Array
(
[gameId] => 123
[gameType] => Match
[char_id] => 1
[stats] => Array
(
[damage] => 55555
[kills] => 5
)
[name] => Char1 // <-- name
)
[1] => Array
(
[gameId] => 157
[gameType] => Match
[char_id] => 2
[stats] => Array
(
[damage] => 12642
[kills] => 9
)
[name] => Char2 // <-- name
)
)
)
Iterate over $arr2 and add the data to it from the matching $arr1 array value:
$i = 0;
foreach($arr2['games'] as $arr2Game){
$id = $arr2Game['char_id'];
$arr2['games'][$i]['name'] = $arr1['data'][$id]['name'];
$i++;
}
Have not tested this code.
If I'm understanding you correctly, you want to add a name index to each of the arrays within the $arr2['games'] array.
foreach($arr2['games'] as $key => $innerArray)
{
$arr2['games'][$key]['name'] = $arr1['data']['Char'.$innerArray['char_id']]['name'];
}

Categories