Append keys to existing array value - php

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"));

Related

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>";

Multidimensional array update

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"
}

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);

creating dimensional array with 2 single array

i have 2 arrays and i want 2 create 2D array for create mysql record
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
i want 2 merge them into 2 dimensional array like this
Array
(
[0] => Array
(
[designation_id] => 1
[judge_name] => a
)
[1] => Array
(
[designation_id] => 2
[judge_name] => b
)
[2] => Array
(
[designation_id] => 3
[judge_name] => c
)
)
i use array_merge_recursive and it generates result like this
Array
(
[0] => a
[1] => b
[2] => c
[3] => 1
[4] => 2
[5] => 3
)
Assuming there will always be the same amount of values in $array1 as there are in $array2..
$array1 = Array("a","b","c");
$array2 = Array(1,2,3);
$newArray = Array();
foreach($array1 as $key => $arr1Val){
$newArray[$key]['designation_id'] = $array2[$key];
$newArray[$key]['judge_name'] = $array1[$key];
}
Of course, you will have to alter $array1 and $array2 to your needs, but you understand the basic idea. Check it here.
Assuming $array1 is the judge_name and $array2 is the designation_id
$newArray = array();
for($i=0; $i<count($array1); $i++)
{
$newArray[] = array(
'designation_id' => $array2[$i],
'judge_name' => $array1[$i]
);
}
Codepad Demo
Outputs
Array
(
[0] => Array
(
[designation_id] => 1
[judge_name] => a
)
[1] => Array
(
[designation_id] => 2
[judge_name] => b
)
[2] => Array
(
[designation_id] => 3
[judge_name] => c
)
)
simple as hell
$array1 = array('a', 'b', 'c');
$array2 = array(1,2,3);
$merged = array();
foreach($array1 as $key => $value)
{
$merged[$key] = array(
'judge_name' => $value,
'designation_id' => array_key_exists($key, $array2) ? $array2[$key] : null
);
}
Assuming that both arrays are of same size
$length = count($array1);
$finalArray = array();
for ($i = 0; $i < $length; $i++) {
$temp = array();
$temp['designation_id'] = $array1[$i];
$temp['judge_name'] = $array2[$i];
$finalArray[$i] = $temp;
}
$a = array('a', 'b', 'c');
$b = array(1,2,3);
$output = array_map(function($i, $j){
return array(
'judge_name' => $j,
'designation_id' => $i
);
}, $a, $b);
var_dump($output);
Outputs
array(3) {
[0]=>
array(2) {
["judge_name"]=>
int(1)
["designation_id"]=>
string(1) "a"
}
[1]=>
array(2) {
["judge_name"]=>
int(2)
["designation_id"]=>
string(1) "b"
}
[2]=>
array(2) {
["judge_name"]=>
int(3)
["designation_id"]=>
string(1) "c"
}
}
If you have PHP >= 5.3 you could use MultipleIterator for that purpose:
$designations = array(1, 2, 3);
$judges = array('a', 'b', 'c');
$mt = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mt->attachIterator(new ArrayIterator($designations), "designation_id");
$mt->attachIterator(new ArrayIterator($judges), "judge_name");
$final = iterator_to_array($mt, false);
print_r($final);
Demo
It iterates over multiple arrays, taking a value from each array at every iterator; you can assign a key for each array that will be used to form a single array item.
Afterwards you convert the results into an array using iterator_to_array().
$new1=array("a","b","c");
$new2=array("1","2","3");
$req=array();
$d=0;
foreach($new1 as $value1)
{
foreach($new2 as $value2)
{
$req[$d]["designation_id"]=$value1;
$req[$d]["judge_name"]=$value2;
$d++;
}
}
echo "<pre>";
print_r($req);

PHP how to join to records from array

Hi it is any way to connect to records where value is the same?
like
[12]=> Array (
[ID] => 127078
[row1] =>
[post] => N16 7UJ
)
[13]=> Array (
[ID] => 127078
[row1] => something
[post] =>
)
and make like that
[12]=> Array (
[ID] => 127078
[row1] => something
[post] => N16 7UJ
)
Here take this function
<?php
$array = array(
12 => array (
"ID" => '127078',
"row1" => '',
"post" => 'N16 7UJ',
),
13 => array (
"ID" => '127078',
"row1" => 'something',
"post" => '',
)
);
function mergedup($array,$matcher){
if(!function_exists('remove_element')){
function remove_element($arr,$element){
$ret_arr = array();
foreach($arr as $val){
if($val !== $element){
array_push($ret_arr,$val);
}
}
return $ret_arr;
}
}
$array = remove_element($array,array());
$return_array = array();
while(isset($array[0])){
$temp = $array[0];
$array = remove_element($array,$temp);
$array_temp = array();
foreach($array as $vals){
if($temp[$matcher]==$vals[$matcher]){
array_push($array_temp,$vals);
foreach($temp as $key => $val){
if(empty($temp[$key])){
$temp[$key] = $vals[$key];
}
}
}
}
foreach($array_temp as $vals){
$array = remove_element($array,$vals);
}
array_push($return_array,$temp);
}
return $return_array;
}
var_dump(mergedup($array,"ID"));
?>
Tested and working
You have so many option such as array_replace
array_merge
foreach
while
Iterator
But i prefer array_replace because you can easily select which array is replacing which
Values
$array[12] = array("ID"=>127078,"row1"=>"","post"=>"N16 7UJ");
$array[13] = array("ID"=>127078,"row1"=>"something","post"=>"");
var_dump($array[12]);
Example array_replace ( http://www.php.net/manual/en/function.array-replace.php )
$array[13] = array_filter($array[13]); //Filter Replacement
$array[12]= array_replace($array[12],$array[13]);
Example array_merge ( http://php.net/manual/en/function.array-merge.php )
//$array[12] = array_filter($array[12]); //Optinal
$array[13] = array_filter($array[13]); //Filter Spaces
$array[12]= array_merge($array[12],$array[13]);
var_dump($array[12]);
Output
array
'ID' => int 127078
'row1' => string 'something' (length=9)
'post' => string 'N16 7UJ' (length=7)

Categories