I have one big array which has a load of similar values but I want to put all the arrays with the same value into another array. For example, I have this array.
array(4) {
[0]=>
array(8) {
["symbol"]=>
string(3) "aaaa"
["name"]=>
string(7) "aaaa"
["buy_price"]=>
string(14) "100.0000000000"
["current_worth"]=>
string(14) "100.2500000000"
}
[3]=>
array(8) {
["symbol"]=>
string(3) "aaa"
["name"]=>
string(7) "aaaaa"
["buy_price"]=>
string(14) "100.0000000000"
["current_worth"]=>
string(14) "100.2500000000"
}
[2]=>
array(8) {
["symbol"]=>
string(3) "xxx"
["name"]=>
string(7) "xxxxx"
["buy_price"]=>
string(14) "100.0000000000"
["current_worth"]=>
string(14) "100.2500000000"
}
}
I want to be able run this array through a foreach loop and then output the array results together that all have the same name. Like too
Name aaa
-- Name aaa [0]
-- Name aaa [1]
Name xxx
-- Name xxx [0]
I am struggling how to do the logic.
If I understand correctly, you need some reducing. Assuming that $origin_array contain what you need to transform:
$result = array_reduce($origin_array, function ($carry, $item) {
$name = $item['name'];
$carry[$name][] = $item;
return $carry;
}, []);
This code will make 2-dimensional array where elements grouped by name field of origin array.
Explanation
The best explanation will be to write analogical foreach loop:
$my_reduce = function ($carry, $item) { // callback, 2-nd param
$name = $item['name'];
$carry[$name][] = $item;
return $carry;
};
$result = []; // initial value, 3 param
foreach($origin_array as $item) {
$result = $my_reduce($result, $item);
}
This is roughly speaking what happens under the hood of array_reduce function.
Related
I know that there are some posts at SO with a similar issue, but none of those could really help me solving mine. I do have the following $test array:
array(1) {
[0]=>
array(4) {
[0]=>
array(2) {
["id"]=>
string(8) "40265656"
["text"]=>
string(29) "10' - 1st Corner - Terengganu"
}
[1]=>
array(2) {
["id"]=>
string(8) "40265715"
["text"]=>
string(25) "18' - 2nd Corner - Pahang"
}
[2]=>
array(2) {
["id"]=>
string(8) "40265770"
["text"]=>
string(29) "23' - 3rd Corner - Terengganu"
}
[3]=>
array(3) {
["id"]=>
string(8) "40265830"
["text"]=>
string(29) "26' - 4th Corner - Pahang"
}
}
}
and would like to extract only those arrays containing Pahang in the ["text"] key. First I have tried
$key = array_search('Pahang', $test);
and that gives me bool(false). What am I doing wrong here?
I think this way will be right:
$result = [];
foreach ($array[0] as $arr) {
if (strpos($arr['text'], "Pahang") !== false) {
$result[] = $arr;
}
}
The function array_search(...) searches for a value inside an array, but your array is not flat, it's multidimensional, this means you have one or more arrays inside another array.
In your case, you can use array_filter(...) that allows you to filter your array elements in a callable function.
So, initially you have to define a function that filters the elements:
function getPahang($element) {
return $element['text'] === 'Pahang'
}
This function returns true when the element text value is equal to 'Pahang', instead it returns false.
Now, you have to call array_filter, by passing your array and the callable function:
$new_array = array_filter($test[0], 'getPahang');
You can try a similar script here: http://sandbox.onlinephpfunctions.com/code/c076222dd6d1c6f2675d0241742e6c11da6eff53
I get this array, but I want to show me KEY and all subitem of that KEY bellow, I dont want every time to repear a key, I need that key shows only one and all others entity that has same key under this one.
array(2) {
[0]=>
array(1) {
["A"]=>
string(2) "Test1"
}
[1]=>
array(1) {
["A"]=>
string(2) "Test1"
}
}
I want something like this:
array(2) {
[0]=>
array(1) {
["A"]=>
string(2) "Test1",
string(2) "Test2"
}
}
use the following:
$return = array_merge_recursive($array, ...);
in your case:
$return = array_merge_recursive($array[0], $array[1]);
but I am guessing you'll want a more dynamic solution, I will draft that up now.
$return = call_user_func_array('array_merge_recursive', $array);
I have an array called $reads when I do an var_dump($reads), I get the below array result.
I am trying to get first item of first array with var_dump($reads[0][0]). I get a Message: Error rendering view: [home.uploaded] Undefined offset: 0
array(161) {
[0]=>
array(4) {
["517a5745e8505"]=>
string(29) "Ngee Ann Poly_Keywords report"
["517a5745e86fe"]=>
string(0) ""
["517a5745e882e"]=>
string(0) ""
["517a5745e89b5"]=>
string(0) ""
}
[1]=>
array(4) {
["517a5745e8505"]=>
string(7) "Keyword"
["517a5745e86fe"]=>
string(6) "Clicks"
["517a5745e882e"]=>
string(11) "Impressions"
["517a5745e89b5"]=>
string(3) "CTR"
}
[2]=>
array(4) {
["517a5745e8505"]=>
string(18) "accounting diploma"
["517a5745e86fe"]=>
string(1) "2"
["517a5745e882e"]=>
string(3) "364"
["517a5745e89b5"]=>
string(5) "0.55%"
}
[3]=>
array(4) {
["517a5745e8505"]=>
string(11) "polytechnic"
["517a5745e86fe"]=>
string(4) "1940"
["517a5745e882e"]=>
string(5) "42995"
["517a5745e89b5"]=>
string(5) "4.51%"
}
[4]=>
array(4) {
["517a5745e8505"]=>
string(15) "tourism diploma"
["517a5745e86fe"]=>
string(1) "1"
["517a5745e882e"]=>
string(3) "156"
["517a5745e89b5"]=>
string(5) "0.64%"
}
Try this
var_dump($reads[0]["517a5745e8505"]);
for what you want as per comments do this, put you array in a $arr variable and follow what I am doing.
$firstelementvalues = array();
$i = 0;
foreach ($arr as $key=>$val) {
$x = 0;
foreach ($val as $value) {
if ($x == 0) {
$firstelementvalues[] = $value;
$x = 1;
}
}
$i++;
}
print_r($firstelementvalues);
Output is
Array
(
[0] => Ngee Ann Poly_Keywords report
[1] => Keyword
[2] => accounting diploma
)
Because there is no value in array with 0 offset so please try like
var_dump($reads[161][0]);
I think that you need to use loop (for,foreach) if you would like to display AND use the data.
var_dump is: Arrays and objects are explored recursively with values indented to show structure.
It's because your array doesn't have element [0][0].
If you want to select first element in second dimension array you can use current:
$lev1 = current($yourArray);
$lev2 = current($lev1);
Your reads array has no numeric keys in the second dimension. You could do something like this, if you have no clue about the keys:
$read = $reads[0];
// I am getting all keys now, because I guess you also want to process the rest of that data
$readKeys = array_keys($read);
var_dump($read[ $readKeys[0] ] );
I have 2 Arrays in 2 variables and both of them containing exactly the same values in the fields (in the 1st array = "image_id"-field and in the 2nd array = "ID-field").
I need to compare the 2 fields and would like to output the imagepath string of the 1st array (if the "ID"-field of 1st array and the field of 2nd array are equal)
Something like this:
if "2146" from 1st multi-array is equal to "2146" from 2nd multi-array, then echo apple.jpg..
But how does that work? Its really freakin me out the last days.. thanks in advance for your replies.
$multidimensional_array1:
array(4) {
[0]=>
string(9) "apple.jpg"
["imagepath"]=>
string(9) "apple.jpg"
[1]=>
string(4) "2146"
["image_id"]=>
string(4) "2146"
}
array(4) {
[0]=>
string(10) "ananas.jpg"
["imagepath"]=>
string(10) "ananas.jpg"
[1]=>
string(4) "2037"
["image_id"]=>
string(4) "2037"
}
array(4) {
[0]=>
string(8) "nuts.jpg"
["imagepath"]=>
string(8) "nuts.jpg"
[1]=>
string(4) "2024"
["image_id"]=>
string(4) "2024"
}
$multidimensional_array2:
array(2) {
[0]=>
string(4) "2146"
["ID"]=>
string(4) "2146"
}
array(2) {
[0]=>
string(4) "2037"
["ID"]=>
string(4) "2037"
}
array(2) {
[0]=>
string(4) "2024"
["ID"]=>
string(4) "2024"
}
As long as the arrays have the same keys, length and order, you can iterate over one and and pick values from both.
$len = count($arr1);
for ($i = 0; $i < $len; $i++)
{
if ($arr1[$i]['image_id'] == $arr2[$i]['ID'])
{
// output $arr1[$i]['imagepath']
}
}
If the information is from two tables in the same database, you would be better off by just joining the tables together. If the arrays are not ordered the same or not of the same length (so that $i might reference different elements in both arrays), use one as a lookup table:
$lookup = array();
foreach ($arr2 as $element)
{
$lookup[$element['ID']] = $element;
}
foreach ($arr1 as $element)
{
if (isset($lookup[$element['image_id']]))
{
// output $element['imagepath']
}
}
foreach($multidimensional_array1 as $arr1){
foreach($multidimensional_array2 as $arr2){
if($arr2['id']==$arr1['image_id']){
echo $arr1['imagepath'];
}
}
}
Note: The larger the arrays become the longer this will take.
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I am creating an array from several text boxes. I am needing to move the elements in the array to insert into the database. Here is the array:
array(2) { [0]=> string(7) "nameone" [1]=> string(7) "nametwo" }
array(2) { [0]=> string(6) "ageone" [1]=> string(6) "agetwo" }
array(2) { [0]=> string(13) "parentnameone" [1]=> string(13) "parentnametwo" }
array(2) { [0]=> string(14) "parentemailone" [1]=> string(14) "parentemailtwo" }
array(2) { [0]=> string(14) "parentphoneone" [1]=> string(14) "parentphonetwo" }
I want to end up with an insert statement such as:
nameone, ageone, parentnameone, parentemailone, parentphoneone
and next row to insert would be
nametwo, agetwo, parentnametwo, parentemailtwo, parentphonetwo
I have tried to create an array with multiple for each loops but I end up with an array that i need to move the keys which brings be back to my original problem.
Is there a method to this madnaess?
Well, lets say your main array contains 5 arrays with 2 elements each. Lets call that $mainArr. "2" in the first line is no. of elements in each subarray. or if the subarraays are not of equal lengths, then the its the length of the largest subarray.
for($i=0;$i<2;$i++) {
foreach($mainArr as $key => $a) {
$ins[$i][] = $a[$i];
} // form an array with insert elements
}
// traverse that to form inserts
foreach($ins as $key => $arr) {
$statements[] = implode(",", $ins[$key]);
}
echo '<pre>';
print_r($statements);
I think thats what you want. If not, let me know. Hope that helps!
$l = count($array[0]);
for ($i=0; $i<$l; $i++) {
// access values like this:
$name = $array[0][$i]; // equals nameone first time and nametwo second time
$age = $array[1][$i];
$parentname = $array[2][$i];
$parentemail = $array[3][$i];
$parentphone = $array[3][$i];
// insert into DB here
}
#!/usr/bin/php
<?php
$val = array('name', 'age', 'parentname', 'parentemail');
$key = array('one', 'two', 'three', 'four', 'five');
$valone = array();
foreach ($val as $k)
array_push($valone, $k.$key[0]);
var_dump($valone);
?>
Outputs :
array(4) {
[0]=>
string(7) "nameone"
[1]=>
string(6) "ageone"
[2]=>
string(13) "parentnameone"
[3]=>
string(14) "parentemailone"
}
Is this what you want you to do ?