Multidimensional array update - php

I am trying to update each language as a multidimensional array to another multidimensional array but it seems to be only saving the last key e.g.(lang_3) but not lang_1 & lang_2. Cracking my head to figure this out. Hope someone can point out my faults. ($country_specs = list of language, $get_code = country code)
$awards = array(
'award_year' => sanitize_array_text_field($_POST['award_year']),
'award_title_user' => sanitize_array_text_field($_POST['award_title_user']),
'award_description_user' => sanitize_array_text_field($_POST['award_description_user'])
);
foreach ($country_specs as $specs => $value) {
if ($value[0] == $get_code ) {
foreach ($value['lang'] as $lang_key => $lang) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_lang = array(
$awards_title => sanitize_array_text_field($_POST[$awards_title]),
$awards_description => sanitize_array_text_field($_POST[$awards_description])
);
update_user_meta($user_id, 'awards', array_merge($awards,$awards_lang));
}
}
}
Current code output example:
Array (
[award_year] => Array (
[0] => 1999-01
[1] => 2010-02 )
[award_title_user] => Array (
[0] => 2
[1] => tt )
[award_description_user] => Array (
[0] => 2
[1] => ddd )
[award_title_lang3] => Array (
[0] => 2CC
[1] => zz )
[award_description_lang3] => Array (
[0] => 2CCCCCCC
[1] => dzz ) )

Working code as follows.
$awards = array(
'award_year' => sanitize_array_text_field($_POST['award_year']),
'award_title_user' => sanitize_array_text_field($_POST['award_title_user']),
'award_description_user' => sanitize_array_text_field($_POST['award_description_user'])
);
$awards_new_lang = array();
foreach ($country_specs as $specs => $value) {
if ($value[0] == $get_code ) {
foreach ($value['lang'] as $lang_key => $lang) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_new_lang[$awards_title] = sanitize_array_text_field($_POST[$awards_title]);
$awards_new_lang[$awards_description] = sanitize_array_text_field($_POST[$awards_description]);
}
}
}
$array_merge_new = array_merge($awards, $awards_new_lang);
update_user_meta($user_id, 'awards', $array_merge_new);
I created a new array ($awards_new_lang) and did an array merge with the old array, thus combining both of the arrays together.

Try this code, it outputs as expected, I tried the mimic the variables structures
<?php
$awards = array(
'award_year' => '1999',
'award_title_user' => '2',
'award_description_user' => '2CCCCCCC'
);
$value = array();
$value['lang'] = array(1, 2, 3);
foreach ($value['lang'] as $lang_key) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_lang = array(
$awards_title => "$lang_key title",
$awards_description => "$lang_key desc"
);
//array merge returns an array, we save the changes here to use them later when the loops are through
$awards = array_merge($awards,$awards_lang);
}
echo '<pre>';
//Final updated version of the array
var_dump($awards);
echo '</pre>';
?>
Outputs:
array(9) {
["award_year"]=>
string(4) "1999"
["award_title_user"]=>
string(1) "2"
["award_description_user"]=>
string(8) "2CCCCCCC"
["award_title_1"]=>
string(7) "1 title"
["award_description_1"]=>
string(6) "1 desc"
["award_title_2"]=>
string(7) "2 title"
["award_description_2"]=>
string(6) "2 desc"
["award_title_3"]=>
string(7) "3 title"
["award_description_3"]=>
string(6) "3 desc"
}

Related

2 arrays match data into 1 array with PHP

I have 2 array's, first array have for example ItemID of my item, second array have description about my item. I want to match data into 1 array.
It looks like:
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
Items in arrays don't have the same value like ID, but they are in the same order so:
Description for the first item in rgInventory is in the first array inside rgDescriptions.
What should I do to match for example id from rgInventory with name from rgDescriptions in the same array for example $backpack = array();?
Regards for you.
Try this:
<?php
$array1 = array('rgInventory' =>
array(
'1234567890' => array(
'id' => 1234567890,
'classid' => 123456789,
'instanceid' => 987654321,
'amount' => 1,
'pos' => 1
)
)
);
$array2 = array(
'rgDescriptions' => array(
'192837465_918273645' => array(
'appid' => 730, 'name' => 'Something')
)
);
Create new function to combine the two arrays into one array:
function array_sum_recursive($data1, $data2) {
if (!is_array($data1) && !is_array($data2)) {
return $data1 + $data2;
}
// deepest array gets precedence
if (!is_array($data2)) {
return $data1;
}
if (!is_array($data1)) {
return $data2;
}
//merge and remove duplicates
$keys = array_unique(array_merge(array_keys($data1), array_keys($data2)));
foreach ($keys as $key) {
if (isset($data1[$key]) && isset($data2[$key])) {
$result[$key] = array_sum_recursive($data1[$key], $data2[$key]);
} else if (isset($data1[$key])) {
$result[$key] = $data1[$key];
} else {
$result[$key] = $data2[$key];
}
}
if(empty($result)){
echo "no result";
die();
}else{
return $result;
}
}
Put the two array in one array $newarray:
$newonearray = array_sum_recursive($array1, $array2);
echo '<pre>';
print_r($newonearray);
?>
And you will get this:
Array
(
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
)
Hope this may help.
You can use function each to get each element of both arrays, then merge its with array_merge and save this new item to backup array.
Try something like this
<?php
$rgInventory = ['firstInv' => ['invId' => 1], 'secondInv' => ['invId' => 2]];
$rgDescriptions = ['firstDesc' => ['descId' => 1], 'secondDesc' => ['descId' => 2]];
if (count($rgInventory) && count($rgInventory) == count($rgDescriptions)) {
$backpack = [];
while($inventory = each($rgInventory)) {
$description = each($rgDescriptions);
$item = array_merge($inventory['value'], $description['value']);
$backpack[] = $item;
}
var_dump($backpack);
}
Output will be:
array(2) {
[0]=>
array(2) {
["invId"]=>
int(1)
["descId"]=>
int(1)
}
[1]=>
array(2) {
["invId"]=>
int(2)
["descId"]=>
int(2)
}
}

How to separate elements from an array values on php and built new array?

i've got this array (from a csv file) :
array (
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
)
How to build a new array that looks like :
[0] : (
'entity_id' => '667',
'commission_book' => '667',
'old_price' => '667',
'new_price' => '667',
);
[1] : (
'entity_id' => '668',
'commission_book' => '668',
'old_price' => '668',
'new_price' => '668',
)
In other words, i want to buid 2 objects using the first array, is there any way to perfom that please ? I'm trying for hours now
This is a simply but elegant way to do that:
<?php
$input = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$output = [];
// drop header entry
array_shift($input);
// process remaining entries
foreach ($input as $key=>$entry) {
$x = &$output[$key];
list(
$x['entity_id'],
$x['commission_book'],
$x['old_price'],
$x['new_price']
) = explode(';', $entry);
}
print_r($output);
The output of the above is:
Array
(
[0] => Array
(
[new_price] => 667
[old_price] => 667
[commission_book] => 667
[entity_id] => 667
)
[1] => Array
(
[new_price] => 668
[old_price] => 668
[commission_book] => 668
[entity_id] => 668
)
)
Short solution with array_slice and array_combine:
$from_csv = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$result = [];
$keys = explode(";", $from_csv[0]); // header fields
foreach(array_slice($from_csv, 1) as $v){
$result[] = array_combine($keys, explode(";", $v));
}
echo '<pre>';
var_dump($result);
// the output:
array(2) {
[0]=>
array(4) {
["entity_id"]=>
string(3) "667"
["commission_book"]=>
string(3) "667"
["old_price"]=>
string(3) "667"
["new_price"]=>
string(3) "667"
}
[1]=>
array(4) {
["entity_id"]=>
string(3) "668"
["commission_book"]=>
string(3) "668"
["old_price"]=>
string(3) "668"
["new_price"]=>
string(3) "668"
}
}
$array = array(
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668');
$array[0] = explode(";",$array[0]);
$array[1] = explode(";",$array[1]);
$array[2] = explode(";",$array[2]);
$newarray = array();
for ($i=0;$i<count($array[0]);$i++){
$newarray[0][$array[0][$i]] = $array[1][$i];
$newarray[1][$array[0][$i]] = $array[2][$i];
}
echo "<pre>";
var_dump($array);
var_dump($newarray);
echo "</pre>";

how to get value from associative array

This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);

Append keys to existing array value

I have the following array and by using array_push & I am getting not the right result.
Array:
Array
(
[0] => 1039
[1] => 417
[2] => 418
)
Array Push:
array_push($array, array("a","b","c"));
Result:
Array
(
[0] => 1039
[1] => 417
[2] => 418
[3] => Array
(
[0] => a
[1] => b
[2] => c
)
)
I want the a,b,c append to value 417 for example .
Disirable result:
Array
(
[1039] => 1039
[417] => Array
(
[0] => a
[1] => b
[2] => c
)
[418] => 418
)
How can this be done?
SOLUTION:
$data = Array (
0 => 1039,
1 => 417,
2 => 418,
);
foreach( $data as $key => $val ) {
$new_data[$val] = 0;
}
foreach( $new_data as $k => $v ){
if( $k == 417 ){
$new_data[$k] = array( 'p' => 50, 'pp' => 75 );
}
}
print_r($new_data);
It doesn't really make sense, but this will do what you show in your example:
$array[1] .= print_r(array("a","b","c"), true);
.= does string concatenation, and passing true as the second argument to print_r makes it return the string that it would have printed.
The result of this is that $array[1] is a string that begins with 417 and is followed by the printed representation of the added array. There's no actual array in there. I'm not sure what you plan to do with this, but it matches your example.
use loop to display new array data
$data = Array (
0 => 1039,
1 => 417,
2 => 418,
);
foreach( $data as $key => $val ) {
if ( $val == 417 ) {
$val = array( 'a','b','c' );
}
$new_data = array( $key => $val );
foreach( $new_data as $key2 => $val2 ) {
if ( is_array( $val2 ) ) {
$val2 = array( 417 => $val );
}
$new_data1 = array( $key2 => $val2 );
print_r($new_data1);
}
}
Don't use array push in this case (granted I might be missing your question)
$arr = array(1,2,3);
$arr[1] = array('a','b','c');
//would output your above example.
Just do it like this & all should work as expected:
array_push($array, "a", "b", "c");
The array_push manual page explains it best:
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
But if the values you are adding are in an array already, then perhaps use array_merge instead:
array_merge($array, array("a","b","c"));
My running php code:
$arr = array(0=>1039,1=>417,2=>418);
array_push($arr, array("a","b","c"));
var_dump($arr);
And var_dump($arr)
array(4) { [0]=> int(1039) [1]=> int(417) [2]=> int(418) [3]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } }
Use array_splice
array_splice($your_arrray, 1, 0, array("a","b","c"));

Splitting up a string - php

I have an array called $result, which is shown below:
array(1)
{ ["response"]=> array(3)
{ [0]=> array(1)
{ ["list"]=> array(2)
{ ["category"]=> string(6) "(noun)"
["synonyms"]=> string(27) "chelonian|chelonian reptile" }
}
[1]=> array(1)
{ ["list"]=> array(2)
{ ["category"]=> string(6) "(verb)"
["synonyms"]=> string(57) "capsize|turn turtle|overturn|turn over|tip over|tump over" }
}
[2]=> array(1)
{ ["list"]=> array(2)
{ ["category"]=> string(6) "(verb)"
["synonyms"]=> string(29) "hunt|run|hunt down|track down" }
}
}
}
I am trying to access the ["synonyms"] element, and split each word and store it in its own string, or perhaps an array of all the words. You can see the words are separated by the | symbol.
I have tried the following code, which did not work (results did not display, so explode did not work) :
$i=0;
foreach ($result["response"] as $value)
{
foreach ($value["list"]["synonyms"] as $temp)
{
$alternative[$i] = explode ("|", $temp);
$i++;
}
}
//OUTPUT THE RESULTS
$j=0;
foreach ($alternative as $echoalternative)
{
echo $j.": ".$echoalternative;
$j++;
}
Any ideas? Thanks guys.
You're trying to iterate over the string in your interior foreach. Try
foreach ($result["response"] as $value)
{
$alternative[$i] = explode ("|", $value["list"]["synonyms"]);
$i++;
}
To create an array of single dimensional arrays (given that you have three groups in your original array), you can do the following:
$out = array();
foreach ($arr['response'] as $key => $value){
$syns = explode('|', $value['list']['synonyms']);
foreach ($syns as $key2 => $value2){
$out[$key][] = $value2;
}
}
To access the single dimensional array for the group of synonyms with index 0, just do the following:
var_dump($out[0]);
Array(
[0] => chelonian
[1] => chelonian reptile
)
If you just want to display the synonyms, you can do something like this:
foreach ($arr['response'] as $key => $value){
$syns = explode('|', $value['list']['synonyms']);
foreach ($syns as $key2 => $value2){
echo $value2.', ';
}
echo "<br />";
}
Output:
chelonian, chelonian reptile,
capsize, turn turtle, overturn, turn over, tip over, tump over,
hunt, run, hunt down, track down,
However, if you want to include that in the original array, you can do this:
array_walk_recursive($arr, function (&$e, $k){
if (preg_match('#[\w\|]+#', $e)){
$e = explode('|', $e);
}
});
var_dump($arr);
Output:
Array(
[response] => Array
[0] => Array(
[list] => Array(
[category] => Array(
[0] => (noun)
)
[synonyms] => Array(
[0] => chelonian
[1] => chelonian reptile
)
)
)
[1] => Array(
[list] => Array(
[category] => Array(
[0] => (verb)
)
[synonyms] => Array(
[0] => capsize
[1] => turn turtle
[2] => overturn
[3] => turn over
[4] => tip over
[5] => tump over
)
)
)
[2] => Array(
[list] => Array(
[category] => Array(
[0] => (verb)
)
[synonyms] => Array(
[0] => hunt
[1] => run
[2] => hunt down
[3] => track down
)
)
)
)
)
The following refactored code should resolve the issue
$i=0;
foreach ($result["response"] as $value)
{
// print_r($value);
$temp = $value["list"]["synonyms"];
// echo $temp;
// foreach ($value["list"]["synonyms"] as $temp)
// {
$alternative[$i] = explode ("|", $temp);
$i++;
// }
}
//OUTPUT THE RESULTS
$j=0;
foreach ($alternative as $echoalternative)
{
print_r($echoalternative);
echo $j.": ".$echoalternative;
$j++;
}

Categories