For example
[Nationality_1] string(8)=>Indian [Nationality_5] string(12)=>American [Nationality_12] string(17)=>Japanese
I got these array values by foreach loop but I want to put these value to single array by index on strings
Desired output
[Nationality] [0] string(8)=>Indian [1] string(12)=>American[2]string(17)=>Japanese
I have tried array_values but output Null
I tried this but creates duplicate array in loop for multiple orders Please help me on it . Thanks
$Nationality[] = $value;
One solution is below code:
$nationality = array(
'Nationality_1' => 'Indian',
'Nationality_2' => 'American',
'Nationality_3' => 'Japanese'
);
$temp = array();
foreach ($nationality as $val) {
$temp[] = $val;
}
$nationality = $temp;
print_r($nationality);
unset($temp);
// Array ( [0] => Indian [1] => American [2] => Japanese )
It sounds like you may want to use array_values to pull all the nationalities from your input list.
array_values
Return all the values of an array
http://php.net/array_values
What you do with that is then up to you but from your desired output it seems you want them under another array with a "Nationality" key?
Here is an example...
$input = array(
'Nationality_1' => 'Indian',
'Nationality_5' => 'American',
'Nationality_12' => 'Japanese'
);
$output = array('Nationality' => array_values($input));
var_dump($output);
/*
array(1) {
["Nationality"]=>
array(3) {
[0]=>
string(6) "Indian"
[1]=>
string(8) "American"
[2]=>
string(8) "Japanese"
}
}
*/
See the code in action: https://eval.in/869938
Related
I have a very big array, I will try to explain the issue in small examples:
Input:
Array (
[alert:accountDisabled:heading] => XYZ
[alert:accountDisabled:message] => XYZ
[alert:accountExpired:heading] => XYZ
[alert:accountExpired:message] => XYZ
[alert:errorResponse:heading] => XYZ
[button:back] => XYZ
)
What I need to get is:
array() {
["alert"]=> array(7) {
["accountDisabled"]=> array(2) {
["heading"]=> string(3) "XYZ"
["message"]=> string(3) "XYZ" }
["accountExpired"]=> array(2) {
["heading"]=> string(3) "XYZ"
["message"]=> string(3) "XYZ" }
["clientError"]=> array(2) {
["heading"]=> string(3) "XYZ"
["message"]=> string(3) "XYZ" }
["errorResponse"]=> array(1) {
["heading"]=> string(3) "XYZ" }
}
["button"]=> array(1) {
["back"]=> string(3) "XYZ"
}
As I said this is a very small example, but the point is to get hierarchy from keys from array number one, hierarchy is divided by this character in key :
I checked for those questions that look similar to this one but they are not helpful lat all
How to access and manipulate multi-dimensional array by key names / path?
Using a string path to set nested array data
SO please read carefully the description of my issue.
I tried to use it for each loop, and I succeed to divide elements from the key, for one element, but I'm not sure where I need to store those hierarchy values for the next elements, any ideas?
$input = [
'alert:accountDisabled:heading' => 'XYZ_1',
'alert:accountDisabled:message' => 'XYZ_2',
'alert:accountExpired:heading' => 'XYZ_3',
'alert:accountExpired:message' => 'XYZ_4',
'alert:errorResponse:heading' => 'XYZ_5',
'button:back' => 'XYZ_6'
];
$results = [];
foreach ($input as $key => $value) {
$arr = explode(':', $key);
$result = $value;
for ($i = count($arr) - 1; $i >= 0; $i--) {
$result = [ $arr[$i] => $result ];
}
$results[] = $result;
}
$result = array_merge_recursive(...$results);
print_r($result);
Output:
Array
(
[alert] => Array
(
[accountDisabled] => Array
(
[heading] => XYZ_1
[message] => XYZ_2
)
[accountExpired] => Array
(
[heading] => XYZ_3
[message] => XYZ_4
)
[errorResponse] => Array
(
[heading] => XYZ_5
)
)
[button] => Array
(
[back] => XYZ_6
)
)
Based on Lukas.j answer, you can use this function:
function parsePath($array, $separator = ':'){
$result = [];
foreach($array as $key => $value){
if(strpos($key, $separator) !== FALSE){
$keys = explode($separator, $key);
$inner_result = $value;
foreach (array_reverse($keys) as $valueAsKey) $inner_result = [$valueAsKey => $inner_result];
$result[] = $inner_result;
}
}
return array_merge_recursive(...$result);
}
I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]
This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
How to remove duplicate values from an array in PHP
(27 answers)
Closed 9 years ago.
First i will like to say that, i have looked into other post but failed trying to accomplish my needs. I have used array_unique($array) but the duplicates don't get discarded. This is a view of my array using var_dump:
{
[0]=>
string(12) "44.94.192.40"
}
array(1) {
[0]=>
string(12) "44.94.192.41"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(13) "44.96.253.100"
}
"44.94.1.1" is a duplicate which i hope to remove but i can't. Does this have to do with my array structure ?
Edited in response to your comment:
From the documentation on array_unique():
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So the fact that each of your values is an array is interfering.
Try creating an array containing just the string values:
$new_array = array();
foreach ($array as $value) {
$new_array[] = $value[0];
}
$new_array = array_unique($new_array);
You can flatten your array and do array unique or do array_map with a reference to a foreign array
<?php
$data = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$visited = array();
array_map(function($v) use ( &$visited ){
if(array_search( $v[0], $visited ) === false){
$visited[] = $v[0];
};
},$data);
var_dump($visited);
array(4) {
[0]=>
string(12) "44.94.192.40"
[1]=>
string(12) "44.94.192.41"
[2]=>
string(9) "44.94.1.1"
[3]=>
string(13) "44.96.253.100"
}
You can find a variety of ways to remove duplicates from a multidimensional array on the php doc page of array_unique in the user comments
http://us3.php.net/array_unique
Orel also mentioned a duplicate question that at a glance also contains a function for doing the same
How to remove duplicate values from an array in PHP
For simplicity I have picked one for you, but depending on exactly what you want, there are many different flavors on the php page I linked
foreach ($arrAddressList AS $key => $arrAddress) {
$arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
$arrAddressList[$key] = unserialize($strAddress);
}
You can do it with a foreach loop
$array = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$temp_arr=array();
foreach($array as $elementKey => $element)
{
foreach($element as $valueKey => $value)
{
if(in_array($value,$temp_arr)) unset($array[$elementKey]);
else $temp_arr[]=$value;
}
}
print_r($array);
Output would be:
Array ( [0] => Array ( [0] => 44.94.192.40 ) [1] => Array ( [0] => 44.94.192.41 ) [2] => Array ( [0] => 44.94.1.1 ) [4] => Array ( [0] => 44.96.253.100 ) )
I have an array that looks like this:
array(3) {
[0]=>
array(2) {
[0]=>
string(10) "2012-11-14"
[1]=>
string(5) "3238"
}
[1]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
[2]=>
array(2) {
[0]=>
string(10) "2012-11-13"
[1]=>
string(5) "3231"
}
I would like to write a foreach loop that would turn this array into:
array(2) {
[0]=>
array(1) {
"2012-11-14" => "3238"
}
[1]=>
array(1) {
"2012-11-13" => "3231"
}
So, basically, I would like to use the array element formatted as Y-M-D date as key to the second element in the array.
Given the following array...
$array = array(
0 => array(0 => "2012-11-14", 1 => "3238"),
1 => array(0 => "2012-11-13", 1 => "3231"),
2 => array(0 => "2012-11-13", 1 => "3231"),
);
putting it into a new array like this:
$new_array = array();
foreach ($array as $key => $item)
{
$new_array[$key][$item[0]] = $item[1];
}
print_r($new_array);
produces this output:
Array
(
[0] => Array
(
[2012-11-14] => 3238
)
[1] => Array
(
[2012-11-13] => 3231
)
[2] => Array
(
[2012-11-13] => 3231
)
)
My answer doesn't get rid of the duplicates, but the added dimension as specified in the original question means that duplicate dates as keys aren't an issue.
<?php
$data = array(
array("2012-11-14", "3238"),
array("2012-11-13", "3231"),
array("2012-11-13", "3231") // warning! when there are two record with same date, the second's count will be display
);
$result = array();
foreach ($data as $value) {
$result[$value[0]] = $value[1];
}
echo '<pre>';
print_r($result);
<?php
$newArray = array();
for($i=0;$i<count($arrayVariable);$i++)
{
$newArray[$arrayVariable[$i][0]] = $arrayVariable[$i][1];
}
echo '<pre>';print_r($newArray);echo '</pre>';
?>
Didn't test it but something like this should work in concept. Of course change arrayVariable to your variable.. but that aside.
You can use this code to get what you want:
$dates = array(
array("2012-11-01", "3238"),
array("2012-11-03", "4321")
);
print_r($dates);
$result = array();
foreach($dates as $value) {
$result[][$value[0]] = $value[1];
}
print_r($result);
The output will look like the requested form:
Array
(
[0] => Array
(
[2012-11-01] => 3238
)
[1] => Array
(
[2012-11-03] => 4321
)
)
Codepad demo: http://codepad.org/XAmUEdYh
However, I would personally prefer Aykut's solution. You would of course have a problem when you've got two records with the same date, but the overall array layout is a bit nicer ;).
Here is what I came up with:
<?php
$original = array(
array(
"2012-11-14",
"3238"
),
array(
"2012-11-13",
"3231"
),
array(
"2012-11-13",
"3231"
)
);
$newArray = array();
foreach($original as $subArray){
$newArray[] = array($subArray[0] => $subArray[1]);
}
var_dump($newArray);
I have a xml parser that returns an associative array. Here's the structure:
<addresses id="123">
<anonymous-address> <test>data 1 </test>
</anonymous-address>
</addresses>
print_r($this->params) will return
Array
(
[addresses] => Array
(
[id] => 123
[anonymous-address] => Array
(
[0] => Array
(
[test] => Array
(
[VALUE] => data 1
)))))
This array then gets passed through list() as:
list($root, $data) = $parsedXML;
Then I attempt to get an id attribute from root and read to do it this way:
$id = $data[$root]['id'];
Edit: This works for all but one $root value which it 400's for. This case of the switch ($root) has the same code as the others, so I have no idea why it errs only there.
var_dump($root, $data) outputs
string (9) "addresses"
array(1) {
["addresses"]=>
array(2) {
["id"]=>
string(3) "123"
["anonymous-address"]=>
array(1) {
["VALUE"]=>
string(7) "data 1 "
}
}
}
$a = list($root, $data);
now $a will be:
array(0 => $root, 1 => $data);
so you can get them like this:
$a[0], $a[1]
so probably
$id = $a[1][$a[0]]['id'];