How to merge array two level become one level in php [duplicate] - php

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

Related

How to get every array element of this json decoded array

With this php code:
$ajaxData = json_encode($_POST['data']);
$jsonDecode = json_decode($ajaxData, true);
var_dump($jsonDecode);
I get this array:
array(1) {
[0]=>
array(5) {
["id"]=>
string(8) "2_page-1"
["x"]=>
string(1) "0"
["y"]=>
string(1) "0"
["width"]=>
string(2) "12"
["height"]=>
string(1) "1"
}
}
How do I get each array element (as a string) so I can use it to put it in database rows?
You have an array inside an array (at the position of 0).
Use a 'for' loop over the first element of the array :
for($i = 0;$i<count($jsonDecode[0]);$i++){
$text = $jsonDecode[0][$i];
}
'$text' contains the string of each element.
This id of course if the output of your json_decode will always return this same syntax : an array inside the first element of an array.
(In my opinion you should change your '$ajaxData' structure - there is no need for that array of only one element - put the data in side one array.

php codeigniter: how to combine two arrays to give more value to the array?

I have two arrays like this
array 1
array(3) { [0]=> int(14) [1]=> int(16) [2]=> int(17) }
array 2
array(3) { [0]=> float(0.46902846738366) [1]=> float(0.40289063077504) [2]=> float(0.54903658244928) }
array 1 is an array that contains the database table id on the value of the associated array.
14, 16, 17 is the id of my database tables.
array 2 is an array that contains the results of mathematical operations that I've done. I have an array is a dynamic array.
so I want to
id 14 has a value of 0.46902846738366
,
id 16 has a value of 0.40289063077504
, and
id 17 has a value of 0.54903658244928
. then each id is stored in each of the variables themselves.
how to combine the two arrays?? thank you!
From your question to combine arrays you can use array_combine to zip array together
<?php
$array_a = [14,16,17];
$array_b = [0.33333, 0.6434, 0.123456];
$zip_array = array_combine($array_a, $array_b);
This will answer your question, as for your comment, if you want to get ids as variable with value you can do this:
extract($zip_array, EXTR_PREFIX_ALL, 'id'); // extract all variable and prefix them with id_
print_r($zip_array);
echo $id_14; // the same as $zip_array[14];
Here I added "id" as a prefix to variables since a variable in PHP can't be a number, you can use any prefix you want
update: as for #u_mulder mentioned you can use array_map() too,better practice would be
$zip_array = array_map(NULL, $array_a, $array_b);
but in this case you can't extract values correctly
If you want to be one array for your keys, and another - for values, than you can use array_combine:
$result = array_combine(
array(14, 16, 17),
array(0.46902846738366, 0.40289063077504, 0.54903658244928)
);
If you want id and value as elements of subarray, then you can use array_map:
$ids = array(14,16,17);
$vals = array(0.46902846738366, 0.40289063077504, 0.54903658244928);
$result = array_map(
function($id, $val) {
return array($id, $val);
},
$ids,
$vals
);
Are you looking for something like this?
Assumes both arrays will be of same size. You can change int,float if you dont want to force, and want a string array instead.
<?php
$array1 = array('1','24','98');
$array2 = array('0.8778','1.764646','6.9488499');
$result = array();
for($i=0;$i<sizeof($array1);$i++){
$result[] =array('0' =>(int)$array1[$i], '1' => (float)$array2[$i]);
}
var_dump($result);
Output
array(3) {
[0]=>
array(2) {
[0]=>
int(1)
[1]=>
float(0.8778)
}
[1]=>
array(2) {
[0]=>
int(24)
[1]=>
float(1.764646)
}
[2]=>
array(2) {
[0]=>
int(98)
[1]=>
float(6.9488499)
}
}
Better practice would be to use the php functions, as mentioned in other answers. This, is a simple way instead.

Is this a mutidimensional array that I can search for key-value?

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.

Sorting php multidimensional array by 2 values in prioritised order [duplicate]

This question already has answers here:
Sort multidimensional array by multiple columns
(8 answers)
Closed 9 years ago.
So im getting very confused about the sorting functions in php, and wondered if someone could point me in the right direction.
The following is a multidimensional array, that i wish to sort first my date, and then by time. Such that if 2 dates are the same, the earlier time will show first.
can this be done and how?
the top array is called $events
Thank you!
array(4) {
[0]=>
array(3) {
["name"]=>
string(4) "Jack"
["date"]=>
string(8) "21.11.13"
["time"]=>
string(5) "17:36"
}
[1]=>
array(3) {
["name"]=>
string(4) "Mike"
["date"]=>
string(8) "21.11.13"
["time"]=>
string(5) "07:30"
}
[2]=>
array(3) {
["name"]=>
string(6) "Thomas"
["date"]=>
string(8) "10.11.12"
["time"]=>
string(5) "18:21"
}
}
You need array_multisort() for this. In your case, you need to extract the columns you want to sort by from your multidimensional array and pass them as params to array_multisort. Here's the solution to your problem:)
/*walk the array and extract the columns needed for sorting*/
foreach($yourarray as $key=>$row){
$date[$key] = $row['date'];
$time[$key] = $row['time'];
}
/*sort the array */
array_multisort($date, SORT_ASC, $time, SORT_ASC, $yourarray);

Need help with PHP array

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

Categories