Can anybody help me out, I'm stuck, don't know how to write a php nested for loop to convert into a key value array.
This is the array structure.
Needed to turn into key value array( combining JobDescription and userdetail array together)
array(2) {
["jobDescription"]=> array(5) {
["funeralFor"]=> string(6) "Myself"
["serviceType"]=> string(1) "1"
["religionType"]=> string(1) "2"
["area"]=> string(4) "2154"
["customerComment"]=> string(6) "fdfddf"
}
["userDetail"]=> array(6) {
["contactEmail"]=> string(16) "fdddf#fffgfg.com"
["contactFirstName"]=> string(6) "fddfdf"
["contactLastName"]=> string(6) "fddffd"
["contactPhoneNumber"]=> string(10) "0420988191"
["signup"]=> array(2) {
["id"]=> string(32) "8048f0f7106c336e1a8825d1d3bec902"
["input"]=> string(3) "k5m"
}
["agreement"]=> string(1) "1"
}
}
Thanks so much in advance
You have two arrays stored in an array. You want the values of both arrays under one array instead of two subarrays?
$newArray = array_merge($array['jobDescription'], $array['userDetail']);
I think you're looking for array_merge, which merges two arrays together:
$new_arr = array_merge($arr['jobDescription'], $arr['userDetail']);
array_merge($bigArray['jobDescription'], $bigArray['userDetail']);
You only need to loop once. No need for nesting. This solution covers where you have an undefined number of arrays to combine. Otherwise, you can use array_merge as suggested by Dickie
$allValues = array();
if(count($mainArray) > 0)
{
foreach($mainArray as $arr)
{
$allValues += $arr;
}
}
The array_merge() function can create an array from multiple arrays. In your example, it works this way:
$yours = array(...);
$values = array_merge($yours["jobDescription"], $yours["userDetail"]);
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
halo everyone. now I'm trying to merge array inside array after query from SQL.. and the result like this
array(3) {
[0]=>
array(1) {
["building_id"]=>
string(1) "1"
}
[1]=>
array(1) {
["building_id"]=>
string(1) "2"
}
[2]=>
array(1) {
["building_id"]=>
string(1) "3"
}
}
I already tried to use this code
$result=[];
foreach($bulding_ids as $arr)
{
$result = array_merge($arr['building_id'],$result);
}
but maybe that is not a answer
I want to that array become like this
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Can I make like that?
You could just use array_column().
$result = array_column($building_ids, 'building_id');
array_column() returns the values from a single column of the input,
identified by the column_key. Optionally, an index_key may be
provided to index the values in the returned array by the values from
the index_key column of the input array.
This eliminates the need for a loop.
Output:
array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" }
The only downside of this, is that all of the building ID's will be stored as strings. If this is a problem for your application, you can easily use array_map() to convert them to ints.
Directly after the line above, do this:
$result = array_map('intval', $result);
array_map() returns an array containing all the elements of array1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
Output:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
You can also make this a single line solution:
$result = array_map('intval', array_column($building_ids, 'building_id'));
But in my opinion this looks a bit more messy.
You need to parse every element in your first array and return the id. Then you convert it into int type. Finally, you save the new value into a new array.
<?php
$bulding_ids[] = ["Building_id" => "1"];
$bulding_ids[] = ["Building_id" => "2"];
$bulding_ids[] = ["Building_id" => "3"];
$result = array();
foreach($bulding_ids as $val){
$result[] = (int)$val['Building_id'];
}
var_dump($result);
I´ve got a question about compairing two (text)arrays. I obtained two arrays from a loop containing numbers as shown below:
array(96) { [1]=> string(2) "20" [2]=> string(2) "18" [3]=> string(2)...
array(96) { [1]=> string(3) "135" [2]=> string(3) "103" [3]=> string(2) "88"
What I want is a new array which contains the difference of the values (1-2). This means that the 2 arrays above will results in the following new (text)array
array(96) { [1]=> string(3) "-115" [2]=> string(3) "-85" [3]=> string(2)
Can someone help me?
You could do this with one foreach-loop. And then substract them from each other. You just need the same count of elements in $array and in $array2.
$new = array();
foreach($array as $key => $val) {
$new[] = (string) ($val - $array2[$key]);
}
If it doesn't matter if the values are integers, you can remove the type casting (string).
this is a function,
function foo($array1, $array2){
$resultArray = array();
for($i=0; i<count($array1); $i++){
$resultArray[] = (string)((int)$array1[$i] - (int)$array2[$i]);
}
return $resultArray;
}
Hope this will help :)
<?php
$a=array(20,18);
$b=array(135,103);
function fr($d,$d1){
global $c;
$c[]=$d-$d1;
}
array_map('fr',$a,$b);
var_dump($c);
Context: I am a novice programmer who has might lack a full 360 degree ability to ask the right questions.
Question:
I have an array $sortablepast:
array(3) {
[0]=> object(SimpleXMLElement)#265 (6) {
["Date"]=> string(25) "2014-12-28T08:15:00-08:00"
["Id"]=> string(5) "78065"
["HomeTeam"]=> string(7) "Man Utd"
["AwayTeam"]=> string(9) "Leicester"
["HomeGoals"]=> string(1) "2"
["AwayGoals"]=> string(1) "2"
}
[1]=> object(SimpleXMLElement)#264 (6) {
["Date"]=> string(25) "2014-12-28T08:15:00-08:00"
["Id"]=> string(5) "78064"
["HomeTeam"]=> string(8) "Man City"
["AwayTeam"]=> string(7) "Burnley"
["HomeGoals"]=> string(1) "3"
["AwayGoals"]=> string(1) "3"
}
[2]=> object(SimpleXMLElement)#266 (6) {
["Date"]=> string(25) "2014-12-28T08:15:00-08:00"
["Id"]=> string(5) "78085"
["HomeTeam"]=> string(9) "Newcastle"
["AwayTeam"]=> string(7) "Everton"
["HomeGoals"]=> string(1) "1"
["AwayGoals"]=> string(1) "1"
}
}
which is the result of a SimpleXMLobject converted into an array using:
<?php $xmlpast = new SimpleXMLElement("xml_past_epl.xml", 0, TRUE);
$sortablepast = array();
foreach($xmlpast->Match as $node) {
$sortablepast[] = $node;
}
?>
I have converted it into an array in order to use usort to sort it in alphabetical order.
I am trying to run an if statement so that if "HomeTeam" = "Man Utd" it will echo "Man Utd are at home".
From the many answers to the question 'How do I search for a key-value pair in a multidimensional array' (including questions that I have asked) I have tried using in_array, issset, array_map, array_filter from answers on SO but none seem to work. I seem to be able access values where key = '0', '1' or '2' but not where key = 'Date, 'Id' etc.
I would therefore like to ask
a) Is this a multidimensional array, or in fact an array of objects? I don't have enough knowledge and experience to know whether the difference is significant
b) If it is not a multidimensional array do I need to convert it in some way or this there a way of searching it for a specific key-value pair (HomeTeam->Man Utd)?
I can give many example of what I have tried that hasn't worked but I thought it would be best to start by asking if there is something in the array that I am misunderstanding.
Everybody seems to jump on the "This is not a multidimensional array." bandwagon.
But this is exactly what you ask, so I'll try to answer your questions:
a) Is this a multidimensional array, or in fact an array of objects? I don't have enough knowledge and experience to know whether the difference is significant
As you noticed, it is in fact an array of object. You can see this because of
array(3) {
[0]=> object(SimpleXMLElement)#265 (6) {
....
}
would have been
array(3) {
[0]=> array(6) {
....
}
if it the XMLObject was also converted to array, it would've been an multideminsional array.
Why is it an array with objects?
Because you haven't converted the nodes them self.
This is what you do:
$sortablepast = array();
foreach($xmlpast->Match as $node) {
$sortablepast[] = $node; // $node is not an array, all nodes within the XML are also SimpleXMLElements
}
Is the difference significant?
Well yes, but you don't need to order or do anything special within the match, so no need to convert it to an array as well. So you just need the correct manipulation on the SimpleXMLElement(see below).
b) If it is not a multidimensional array do I need to convert it in some way or this there a way of searching it for a specific key-value pair (HomeTeam->Man Utd)?
No need you can still read the SimpleXMLElement.
For example:
foreach ($sortablepast as $match) {
//$match is a SimpleXMLElement
if ($match->HomeTeam == 'Man Utd') {
echo 'Man Utd are at home';
}
}
How to sort:
//Sort by HomeTeam alphabetically
usort($sortablepast, function($a, $b)
{
if ($a->HomeTeam == $b->HomeTeam) {
return 0;
}
return ($a->HomeTeam < $b->HomeTeam) ? -1 : 1;
});
This is not a multidimensional array. It is s single dimensional array of objects.
You have array with three elements, where every element is object of a SimpleXMLElement class.
echo $array[2]->HomeTeam;
echo $array[1]->Id;
etc.
I hope that Reference (click!) will help you
it looks like you have a array of objects rather than a multidimensional array. array size is 3, see first line of code.
I have an array that looks like this when I use var_dump:
array(4) {
[0]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
[1]=> array(2) {
[0]=> string(1) "2"
["userID"]=> string(1) "2"
}
[2]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
[3]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
}
That is 1,2,1,1
I tried using array_unique($arr) but on this particular array, instead of turning it into 1,2, it just turns the array into 1.
It should work, but I'm not sure why it doesn't.
array_unique only removes elements that are equal by their string value. That is not the case for sub-arrays.
You will need to iterate over the array manually (after sorting with a user function) and unset the doubles. Not pretty, sorry.
I am going to guess that all you care about is knowing which userIDs exist in the result set. Therefore, I will flatten the array first. After doing so, I can apply array_unique to obtain only the unique values. As others have stated, array_unique is not designed to work with multidimensional arrays.
$flattened = array_map(
function($e) { return $e['userID']; },
$array
);
$unique = array_unique($flattened);
If you like foreach loops, then it would look like this.
$flattened = array();
foreach ($array as $v) {
$flattened[] = $v['userId'];
}
$unique = array_unique($flattened);
There is also an alternative to finding unique elements which offers a performance boost over array_unique -- O(n) time complexity versus O(nlogn). That is, array_unique($array) is equivalent to array_keys(array_flip($array)).
A kind of quick and dirty method might be to iterate over all elements, serialize the values and use these as keys in a new array that contains their values as well then use array_values() on that array like this:
<?php
function array_unique_recursive(array $a) {
$result = array();
foreach ($a as $item)
$result[serialize($item)] = $item;
return array_values($result);
}
?>
<?php
$arr = array(
array ( 0=>"1",
userID=>"1"),
array ( 0=>"2",
userID=>"2"),
array ( 0=>"1",
userID=>"1"),
array ( 0=>"1",
userID=>"1"));
$arr_unique=array_unique($arr);
echo '<pre>';
var_dump($arr_unique);
echo '</pre>';
?>
Try using sort regular filter ...
<?php
$arr = array_unique($arr, SORT_REGULAR);
?>
I've got two arrays, for which var_dump give the following values:
$array1:
Artifacts:array(2) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } [1]=> array(3) { [0]=> string(7) "module2" [1]=> string(17) "path/to/file2.txt" [2]=> string(0) "" } }
$array2:
Artifacts:array(1) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } }
I would think that doing array_diff($array1,$array2) would give me an array countaining only the second elements. Instead I got an empty array. I try switching the parameters, and still an empty_array, but this time without surprise. Wouldn't array_diff work on arrays of arrays?
From the documentation:
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
echo (string) array(); gives you just Array, so for array_diff, your arrays look like:
$array1 = array('Array', 'Array');
$array2 = array('Array');
So to create a diff for your arrays, you would need something like this (assuming that every element in the arrays is itself an array):
$diff = array();
foreach($array1 as $val1) {
$contained = false;
foreach($array2 as $val2) {
if(count(array_diff($val1, $val2)) == 0) {
$contained = true;
break;
}
}
if(!$contained) {
$diff[] = $val1;
}
}
Disclaimer: This is more or less just a sketch.
From the array_diff documentation.
This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);
From the array_diff manual page: "This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);."
Asked and answered here:
recursive array_diff()?