Extract 1st value from a multidimensional array [duplicate] - php

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
My array is like: (Below is the dump extract)
array(3) {
[0]=> array(2) {
[0]=> string(4) "0013"
[1]=> float(28.936563322435)
}
[1]=> array(2) {
[0]=> string(4) "0003"
[1]=> float(35.514521271921)
}
[2]=> array(2) {
[0]=> string(4) "0007"
[1]=> float(47.577230340278)
}
I would like to extract its 1st value like 0013 or 0007 etc into a variable say $order such that the final result is something like this
$order= "0013,0003,0007";
I tried to do something like this:
foreach($array as $x){
$order = x[0].",";
}
BUT it only extracts the first element

You can do it using array_map() and implode():
$order = implode(',', array_map(function($a) { return $a[0]; }, $array));
// string '0013,0003,0007' (length=14)
Or, if you're using PHP 5.5 or above:
$order = implode(',', array_column($array, 0));

To achieve what you desire you can use
$order = implode(',', array_column($array, 0));

for($i=0; $i<count($array); $i++){
$res[$i]=$array[$i][0];
}
$order=implode(",", $res);
This will give you a string with the first values of your nested arrays, all comma-separated.

$arr = array();
foreach($a as $k=>$v){
$arr[] = $v[0];
}
$order = implode(',', $arr);

Related

How to remove records in php array where there are same values in one column [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
I've a array of associative array
array(xxx) {
[0]=>
array(3) {
["group_id"]=>2
["contact"]=> "foo"
["contact_email"]=> "foo#gmail.com"
}
[1]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
[2]=>
array(3) {
["group_id"]=>2
["contact"]=> "foobar"
["contact_email"]=> "bar#gmail.com"
}
[3]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
to remove duplicate arrays I do this
array_unique( $array, SORT_REGULAR );
But now I would like to do something more specific by eliminating only the arrays that have duplicated key value (contact_email) to obtain this result
array(xxx) {
[0]=>
array(3) {
["group_id"]=>2
["contact"]=> "foo"
["contact_email"]=> "foo#gmail.com"
}
[1]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
How could i do that?
Thank you
Extract to an array and index by contact_email. Since there cannot be duplicate indexes you'll get the last occurrence:
$array = array_column($array, null, 'contact_email');
If you want to re-index that back to integers:
$array = array_values(array_column($array, null, 'contact_email'));
You can use foreach and group them by contact_email
$r = [];
foreach($a as $v){
$r[$v['contact_email']] = $v;
}
print_r(array_values($r));// reorder index
Working example : https://3v4l.org/0oN8h
I think this can help
$arr = [['contact_email' => 'a#a.com'], ['contact_email' => 'a#a.com'], ['contact_email' => 'b#a.com']];
$result = [];
array_map(function ($item) use (&$result) {
$result[$item['contact_email']] = $item;
}, $arr);
print_r($result);

Getting array values of inner array keys [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 6 years ago.
I have an array like this:
array(2) {
[0]=>
array(1) {
[0]=>
object(Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter)#13 (2) {
["name":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(2) "name1"
["value":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(2) "30"
}
}
[1]=>
array(2) {
[0]=>
object(Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter)#12 (2) {
["name":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(2) "name2"
["value":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(6) "289213"
}
[1]=>
object(Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter)#15 (2) {
["name":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(6) "name3"
["value":"Bas\WWW\Router\Route\URIs\URI\Parameters\Parameter\Parameter":private]=>
string(5) "00123"
}
}
}
And I want to retrieve all objects in it, which are the values of the inner array keys.
My approach was by looping the first outer values, then looping the inner values and placing those in a seperate array.
$a = [];
foreach ($parameters as $parameter) {
foreach ($parameter as $data) {
$a[] = $data;
}
}
Is there a better way for doing this instead of looping both of the arrays?
Simple solution is merge your sub_arrays, treating your array as a list of arguments to array_merge:
$a = call_user_func_array('array_merge', $parameters);
Simple solution using array_walk_recursive function:
$result = [];
array_walk_recursive($parameters, function($v) use(&$result){ $result[] = $v; });
http://php.net/manual/en/function.array-walk-recursive.php

How to calculate values of array?

I want to get the sum of all the values in array in php. Here I have array
$_SESSION['price'][];
I have some values in the array which has been inserted in to array in each iteration.
when do var_dump($_SESSION['price']); of array I am getting
array(1) { [0]=> string(4) "4806" } array(1) { [0]=> string(5) "65000" } array(1) { [0]=> string(5) "44005" } array(1) { [0]=> string(6) "215668" } array(1) { [0]=> string(4) "7896" }
now I want to calculate each value i.e 4806+ 65000+44005+215668+7896
How can I do this?
I tried echo "totalsum".array_sum($_SESSION['cart_total']);
but I got the output
totalsum4806totalsum65000totalsum44005totalsum215668totalsum7896
You can simply use array_sum like as
echo array_sum(call_user_func_array('array_merge', $arr));
Or for PHP > 5.5.0 You can also use array_column like as
echo array_sum(array_column($arr,0));
Output:
337375
Demo
Apparently you have a 2-dimensional array. Every element of $_SESSION['price'] is an array with one element, rather than a price. I'm not sure why you did it that way, but you'll need to write a loop to access them.
$sum = 0;
foreach ($_SESSION['price'] AS $subarray) {
$sum += $subarray[0];
}
Maybe you should fix whatever is creating the session variable so it makes it a 1-dimensional array. The sub-arrays don't seem to serve any purpose.
Try this: I've manipulated your array
$arr = $_SESSION['price'];
foreach($arr as $key => $val)
{
$newVal[] = $val[0];
}
print_r(array_sum($newVal)); //output is 337375
Normally, you would sum an array like this:
$sum = array_sum($_SESSION['price']);
However, this will not work for you for two reasons:
Your values are not stored as integers, but as strings (hence the " in the var dump). (OK, array_sum might convert it to an integer for you, so perhaps this is not a problem in practice.)
Your values are not stored as elements in the array, but for some reason as single elements in a sub array (hence the array(1) { [0]=> in the var dump).
If there are no reasons to why you would want to have it like that, the easiest solution would be to just fix those two things when the array is created, so instead of a nested array of strings you have a flat array of integers.
If that is not possible for some reason, you can sum it like this:
$sum = 0;
foreach($_SESSION['price'] as $e) {
// Convert the first element of the sub array to integer and add it to the $sum.
$sum += (int)$e[0];
}
I think you use $_SESSION['cart_total'], but you have to use like $_SESSION['price']. When the code is like below
$a = array("price" => array("4806", "65000", "44005", "215668", "7896"));
var_dump($a["price"]);
echo "<br>";
echo "totalsum = " . array_sum($a["price"]);
The output will look like below
array(5) { [0]=> string(4) "4806" [1]=> string(5) "65000" [2]=> string(5) "44005" [3]=> string(6) "215668" [4]=> string(4) "7896" }
totalsum = 337375
OR
$a["price"][] = array("4806");
$a["price"][] = array("65000");
$a["price"][] = array("44005");
$a["price"][] = array("215668");
$a["price"][] = array("7896");
$sum = 0;
foreach ($a["price"] AS $price) {
$total += $price[0];
}
echo $total;

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.

Trying to extract values from a multidimensional array to use in a SQL statement [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I've got an array which when I var_dump looks like this:
array(2) { [0]=> array(1) { ["unit_id"]=> string(1) "1" } [1]=> array(1) { ["unit_id"]=> string(1) "3" } }
I need to extract each of those values (1, 3) to where I can put them in a SQL WHERE IN clause
So far I've found the php implode function but I do not know how to do that on a multidimensional array.
Please help :(
Try this code:
$arr = array( // your array
array("unit_id"=>1),
array("unit_id"=>3)
);
$str = implode(',', array_map(function($el){ return $el['unit_id']; }, $arr));
If you are using php version >= 5.5, then try:
echo implode(",",array_column($arr,'unit_id'));
If not then try:
$res = array();
foreach($arr as $ar){
$res[] = $ar['unit_id'];
}
echo implode(",",$res);
See demo here

Categories