I got a PHP array which looks like that:
array(3) {
[0] => array(3) {
["Row"] => string(1) "1"
["Col"] => string(1) "1"
["Value"] => string(4) "lbl1"
}
[1] => array(3) {
["Row"] => string(1) "2"
["Col"] => string(1) "1"
["Value"] => string(4) "lbl2"
}
[2] => array(3) {
["Row"] => string(1) "3"
["Col"] => string(1) "1"
["Value"] => string(4) "lbl3"
}
}
I know that every pair "Row" and "Col" is different from the others. I can't change the way I'm creating the array.
Can I somehow access the array kinda like a hash table like this: arr[Row => 0][Col => 0] and get the value which is in Row 0 and Col 0?
If I understand your question well, you would need to reformat you array in order to access it like so: $array[1][1] to get Value of lbl1.
Try this where $array is your initial Array.
<?php
$return = array();
foreach($array as $value)
$return[$value['Row']][$value['Col']] = $value['Value'];
var_dump($return[1][1]); // outputs "lbl1"
Not sure why you need col and row as fields. Could you the key of the primary array as one? If it's a 2 dimensional array with just col/row, you should be able to create your array just use the keys properly.
$foo[1][1]="lbl1";
$foo[2][1]="lbl2";
$foo[3][1]="lbl3";
It's just as simple to access then, $foo[1][1] returns "lbl1"
You can use array_walk to get the value:
<?php
$a = array(
0 => array(
"Row" => "1",
"Col" => "1",
"Value" => "A",
),
1 => array(
"Row" => "2",
"Col" => "1",
"Value" => "B",
),
2 => array(
"Row" => "3",
"Col" => "1",
"Value" => "C",
)
);
$rowNeedle = 3;
$colNeedle = 1;
$result = null;
array_walk($a, function($row, $key) use($rowNeedle, $colNeedle, &$result) {
if($row['Row'] == $rowNeedle && $row['Col'] == $colNeedle) $result = $row['Value'];
});
echo $result;
The code will return the last match in case the array contains more than one row with the same Row and Col value (though, as you said, that is not your case).
Related
I want to get all with the same id_attribute_group and show them but the arrays with the same id_attribute_group are spread apart. I would like tho loop through them multiple times.
array(8) {
["id_attribute"] => string(1)
"1" ["id_attribute_group"] => string(1)
"1" ["attribute"] => string(1)
"S" ["group"] => string(4)
"Size" ["reference"] => string(6)
"demo_1"
}
array(8) {
["id_attribute"] => string(2)
"11" ["id_attribute_group"] => string(1)
"2" ["attribute"] => string(5)
"Black" ["group"] => string(5)
"Color" ["reference"] => string(6)
"demo_1"
}
array(8) {
["id_attribute"] => string(1)
"2" ["id_attribute_group"] => string(1)
"1" ["attribute"] => string(1)
"M" ["group"] => string(4)
"Size" ["reference"] => string(6)
"demo_1"
}
so it should loop once and get all with same number and assign them,loop again and get all with the second one and so on.
Without knowing more about your use case it's hard to tell for certain. However, it seems to me that a simple sorting algorithm (which effectively groups the array by id_attribute_group) followed by a loop to output is all you need:
Code
// Input array
$array = [
[
"id_attribute" => "1",
"id_attribute_group" => "1",
"attribute" => "S",
"group" => "Size",
"reference" => "demo_1",
],
[
"id_attribute" => "11",
"id_attribute_group" => "2",
"attribute" => "Black",
"group" => "Color",
"reference" => "demo_1",
],
[
"id_attribute" => "2",
"id_attribute_group" => "1",
"attribute" => "M",
"group" => "Size",
"reference" => "demo_1",
],
];
// Sort with reference to id_attribute_group
uasort($array, function($a,$b){
return $a["id_attribute_group"] <=> $b["id_attribute_group"];
});
// Output data
foreach($array as $item){
echo "{$item["group"]} {$item["attribute"]}\n";
}
Output
Size S
Size M
Color Black
Notes
Here the uasort sorts by the value id_attribute_group in each sub array.
Using uasort we maintain the original keys so you can always resort etc.
If you want to do something different with each group (e.g. separate them out) then you can update the code to something like:
Additional Code
uasort($array, function($a,$b){
return $a["id_attribute_group"] <=> $b["id_attribute_group"];
});
$last = false;
foreach($array as $item){
if($last && $last != $item["id_attribute_group"]){
echo PHP_EOL;
}
echo "{$item["group"]} {$item["attribute"]}\n";
$last = $item["id_attribute_group"];
}
Output
Size S
Size M
Color Black
Updated Solution
It's probably easiest to reformat your array first and then loop over the details you need:
$transformArray = [];
foreach($array as $item){
$transformArray[$item["id_attribute_group"]][] = $item;
}
foreach($transformArray[2] as $color){
echo "{$color["attribute"]} ";
foreach($transformArray[1] as $size){
echo "{$size["attribute"]} ";
}
echo PHP_EOL;
}
// Output: Black S M
My problem is so twisted that I don't even know how to start to explain it.
Lets say that I have several assosiative arrays (not always the same arrays: sometimes I have the products array, sometimes I have the markets array, sometimes I have the segment array, etc...). $values is the only array I always get!
$values = array ("0" => "1", "4" => "2", "5" => "3");
$products = array ("0" => "1", "1" => "1", "2" => "2", "3" => "1", "4" => "2", "5" => "3");
$markets = array ("0" => "1", "3" => "1", "4" => "2", "5" => "3");
...
I want to build an array with the values of each of the arrays I get, with the values matching the keys.
Something like
$myArray = array ("0" => array ( "values" => "1", "products" => "1", "markets" => "1"),
"1" => array ( "products" => "1"),
"2" => array ( "products" => "2"),
"3" => array ( "products" => "1", "markets" => "1"),
"4" => array ( "values" => "2", "products" => "2", "markets" => 2),
...);
I've tried something like this:
switch ($_POST["cpv_type"]) {
case "pClass":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productClasses";
break;
case "pMarket":
$keyValue = $_POST["cpv_type"];
$objKey = "this->markets";
break;
case "pSegment":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productSegments";
break;
case "pType":
$keyValue = $_POST["cpv_type"];
$objKey = "this->productTypes";
break;
default:
$keyValue = "products";
$objKey = "this->products";
break;
}
And then I do a foreach cicle:
// all values must be floats
if(!empty($this->value)){
foreach ($this->value as $key => &$curVal){
// if no value has been entered, exclude it and also associated product from validation
if (strlen(trim($curVal)) == 0) {
unset($this->value[$key]);
unset($this->products[$key]);
} else {
// This validates my variable
$curVal = TMS::checkVar($curVal, "dec", $_SESSION["dico"]->_VALUE_, 100, false);
// Store the value on existing array, associating "hoppValue" to the right key entry!
$logDetail[$keyValue][${$objKey}[$key]]["hoppValue"] = $curVal;
}
}
}
My problem is in the variable variable:
How do I access, for example $this->productTypes[5] using variable variable syntax?
I get "null" for all var_dumps of $$objKey, ${$objKey}, ${$objKey}[$key], ${$objKey[$key]}, $$objKey[$key]
Thank you for your help!
you can simple get array in case $objKey = $this->productClasses and used as $objKey[$key]. And you can replace $objKey to $arrayClasses or similary for good understending code.
p.s. sorry for my English.
I have two multidimensional arrays of the same structure.
Like this:
array(2) {
[0] =>
array(9) {
'id' =>
string(5) "44994"
'ersatzteil_id' =>
string(3) "120"
'lang' =>
string(6) "name2_tag2"
'title' =>
string(12) "Seitentüren"
'alias' =>
string(12) "seitentueren"
'content' =>
string(1610) "LOREM ISPUM BLALABLBL"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "1"
'short_text' =>
NULL
}
[1] =>
array(9) {
'id' =>
string(5) "44996"
'ersatzteil_id' =>
string(3) "122"
'lang' =>
string(6) "name1_tag1"
'title' =>
string(7) "Spoiler"
'alias' =>
string(7) "spoiler"
'content' =>
string(1513) "SOME OTHER RANDOM TEXT"
'on_main' =>
string(1) "0"
'disabled' =>
string(1) "0"
'short_text' =>
NULL
}
}
What I need to do is I need to compare first array with the second one.
I have to compare them by keys ersatzteil_id and content , and I find that they have same content I need to store element from first array in another new array, that wasn't existing before.
For example I need something like this, but more efficient:
if(array1[20]['ersatzteil_id'] == array2[145]['ersatzteil_id']
&& array1[20]['content'] == array2[145]['content']){
array3 = array1[20];
}
Try this code:-
$result = [];
foreach($array1 as $arr1){
foreach($array2 as $arr2){
if(($arr1['id'] == $arr2['id']) && ($arr1['ersatzteil_id'] == $arr2['ersatzteil_id'])){
$result[] = $arr1;
}
}
}
echo '<pre>'; print_r($result);
I'm trying to manipulate an associative multidimensional array. I've extracted the keys from an array that I want to apply to another's values . . .
These are the keys that I've extracted in another function
$keys = array (
"id" => "id",
"addr_street_num" => "addr_street_num",
"addr_street" => "addr_street",
"price" => "price",
"days" =>"days",
"state" => Array
(
"id" => "id",
"name" => "name"
),
"city" => Array
(
"id" => "id",
"web_id" => "web_id",
"name" => "name"
)
);
This array has the values I'd like to combine together
$vals = array (
"0" => "830680",
"1" => "20",
"2" => "Sullivan Avenue",
"3" => "333000",
"4" => "12",
"5" => Array
(
"0" => "4",
"1" => "Maryland",
),
"6" => Array
(
"0" => "782",
"1" => "baltimore",
"2" => "Baltimore",
)
);
When I try to do array_combine($keys, $val);
I get 2 Notices about Array to string conversion
I guess array_combine only works on one dimensional arrays, any ideas on how to approach this?
If $keys was modified could it be combined with the values - problem is the shape of $keys is what I want to end up with?
It can be done recursively.
function combine_recursive($keys, $values) {
$result = array();
$key = reset($keys);
$value = reset($values);
do {
if (is_array($value)) {
$result[key($keys)] = combine_recursive($key, $value);
} else {
$result[key($keys)] = $value;
}
$value = next($values);
} while ($key = next($keys));
return $result;
}
This works for me with your example arrays. I'm sure this will give you all kinds of weird results/errors if the array structures are different from each other at all.
I am extracting data from an xls document which returns as an array. The array keys however is not numeric, but resembles the cell column alphabetical digit. So effectively I have an array like this:
// Example array:
$array = array(
[0] => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
[1] => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
[2] => array(
"A" => "",
"B" => "",
"C" => "",
"D" => ""
)
);
Now the problem with the returned array is it does not filter the array at all, and I may have rows and rows of empty values in the rows.
I need a way to either clean up the array completely so remove empty rows and digits, but this may give me some issues with array consistancy later.
What I am looking for is a function which can chop rows in an array by a alphebitical digit. So effectively something like array_chop($array","C"); which would then effectively unset all the remainder rows key and value pairs from D onwards.
Is this possible? Is there a php function already I can use? I am sorry that I cannot provide sample code but I have no idea where to start. The array is substancially large, so I am looking for a memory efficient solution.
Thank you in advance!
If you want to copy only a small first portion of the column, this must be efficient:
<?php
$array = array(
0 => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
1 => array(
"A" => "Name",
"B" => "Surname",
"C" => "",
"D" => "Telephone"
),
2 => array(
"A" => "",
"B" => "",
"C" => "",
"D" => ""
)
);
$last_column = 1;
$n = count($array);
for ($i = 0; $i < $n; ++$i)
{
$copy = array();
$j = 0;
foreach($array[$i] as $key => $value)
{
if ($j <= $last_column)
{
$copy[$key] = $value;
++$j;
}
else
{
$array[$i] = $copy;
break;
}
}
}
var_dump($array);
This leaves only name and surname in the matrix:
array(3) {
[0]=>
array(2) {
["A"]=>
string(4) "Name"
["B"]=>
string(7) "Surname"
}
[1]=>
array(2) {
["A"]=>
string(4) "Name"
["B"]=>
string(7) "Surname"
}
[2]=>
array(2) {
["A"]=>
string(0) ""
["B"]=>
string(0) ""
}
}