I have an array like this
Array
(
[0] =>
[
"18.06.2016",
"18.06.2016",
"18.06.2016",
"Test Test",
"Test Name",
"Michael Dean",
"London",
"1",
"980.00",
"",
"",
"875.00",
"875.00",
"0",
"64.81",
"0",
"810.19"
]
[1] =>
[
"18.06.2016",
"18.06.2016",
"18.06.2016",
"Tray 1",
"Test Name",
"Adam Richards",
"London",
"1",
"980.00",
"",
"",
"105.00",
"105.00",
"0",
"7.78",
"0",
"97.22"
]...
I want to check if the array key value has 1, after London or not?
Like in the first array key, the value goes like this order:
...,"Test Name","Michael Dean","London","1",...
How can I do that?
If the order is always the same you can just loop through.
foreach ($array as $key => $value) {
if ($value[4] == 'London' && $value[5] == 1) {
echo '$array['.$key.'] has London and 1 as key 4 and 5';
}
}
Though you have not appointed keys to the sub-arrays, they still have default keys and you can use these to get to the values you want.
Edit
Taking a look at your array I see that there is no logic to the order of the keys. You will not be able to find the values you are looking for unless you assign keys such as town, id, date, name to them.
For example:
array(
'0' => array(
'name' => 'John Doe',
'town' => 'London',
'active' => 1,
)
);
Use regular foreach loop to check if London value is followed by 1:
// $arr is your initial array
foreach ($arr as $k => $v) {
if ($v[6] == 'London') {
$hasValue = ($v[7] != 1)? "NOT" : "";
echo "Item with key $k has 'London' which is $hasValue followed by 1". PHP_EOL;
}
}
The exemplary output:
Item with key 0 has 'London' which is followed by 1
Item with key 1 has 'London' which is followed by 1
...
Related
I have this array:
array: [
0 => array: [
"key 1" => "user 1",
"count" => "14"
],
1 => array: [
"key 2" => "user 2",
"count" => "7"
],
2 => array: [
"key 2" => "user 1",
"count" => "1"
]
]
I have to count the count values for each key. But the names of keys have different names. And I do not know how to get access to them.
I want to get such result:
array: [
0 => array: [
"user" => "user 1",
"key 1" => "14",
"key 2" => "1",
],
1 => array: [
"user" => "user 2",
"key 2" => "7"
]
I tried to use two foreach loops
foreach ($result as $k=>$v)
{
foreach ($v as $k2=>$v2) {
$final[]["user"] = $result[$k][$k2];
}
}
But the result is incorrect
You could try something like this :
$result = [
["key 1" => "user 1", "count" => "14"],
["key 2" => "user 2", "count" => "7"],
["key 2" => "user 1", "count" => "1"]
];
$out = [] ; // output array
foreach ($result as $val) {
$keys = array_keys($val); // get the keys "key 1", "count" as array
$uid = reset($val); // get the first value "user 1"
$out[$uid]['user'] = reset($val); // store the user name
$out[$uid][reset($keys)] = $val['count']; // store the count into "key N" key.
}
$out = array_values($out); // reindex keys
print_r($out); // output data (optional)
Outputs :
Array
(
[0] => Array
(
[user] => user 1
[key 1] => 14
[key 2] => 1
)
[1] => Array
(
[user] => user 2
[key 2] => 7
)
)
I assumed user x and key x were just placeholders for any values.
$b = array();
foreach ($a as $row)
{
$values = array_values($row);
$keys = array_keys($row);
//Extract data from keys / values
$user = $values[0];
$key = $keys[0];
$count = $values[1];
//Create element in output array and insert user info
if ( ! isset($b[$user]))
{
$b[$user] = array('user' => $user);
}
//Add key info
$b[$user][$key] = $count;
}
//Rewrite array keys to 0, 1, 2, ...
$b = array_values($b);
edit: comments added
I have array inside array:
{
"0" => array("key" => "code", "id" => "4", "value" => "yes"),
"1" => array("key" => "parameter", "id" => "4", "value" => "0"),
"2" => array("key" => "code", "id" => "5", "value" => "no"),
etc...
}
This is what I want to do: I want to have one dimension array in which key would be "id" and value would be "value". However, I need to filter out entries whose key is "parameters". So, in this example, the final array should look like this:
{
"4" => "yes",
"5" => "no"
}
I just can't seem to figure out how to do this. Could you please help me a bit? I tried writing this foreach inside foreach but I just can't wrap my head around how to filter data.
foreach ($settings AS $key => $value) {
$id = null;
$value = null;
foreach ($value AS $key2 => $value2) {
// No idea how to filter out uneccesary entries and save the correct ones
}
$finalArray[$id] = $value;
}
This should do it :
$finalArray = array();
foreach ($settings as $setting) {
if ($setting['key'] != 'parameter') {
$finalArray[$setting['id']] = $setting['value'];
}
}
Assuming all your entries have keys 'key', 'id' and 'value'.
use array_column and array_filter like this, if you want to filter more keys add them to out_keys array :
<?php
$array = [
["key" => "code", "id" => "4", "value" => "yes"],
["key" => "parameter", "id" => "4", "value" => "0"],
["key" => "code", "id" => "5", "value" => "no"]
];
$out_keys = ['parameter'];
$result = array_column(array_filter($array, function($item) use($out_keys) {
return !in_array($item['key'], $out_keys);
}), 'value', 'id');
echo "<pre>";
print_r($result);
output:
Array
(
[4] => yes
[5] => no
)
Assuming $data is your starting array, the code below will output what you want in $result
$result = [];
foreach(array_filter($data, function($el){return $el['key']!='parameter';}) as $el){
$result[$el['id']] = $el['value'];
}
Live demo
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 am trying to compare two arrays and update specific array values based on conditions.
Getting attendance array of absent students:
$array1 =
array(
array("student_id" => "2",
"date" => "2016-04-24"),
array("student_id" => "6",
"date" => "2016-04-24"));
$attendance = json_decode(json_encode($array1));
Getting student list array of all students:
$array2 =
array(
array("student_id" => "1",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "2",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "3",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "6",
"Reason" => "1",
"date" => "2016-04-24"));
$students = json_decode(json_encode($array2));
Taking out only student IDs of absent students:
foreach($attendance as $att)
{ $atts[] = $att->student_id;}
Here I am trying to find out if any of the students ID in student array matches with ID in absent array. If ID is present then I will update the Reason as "1". Else will make the reason as 0
for ($i = 1; $i <= count($students); $i++) {
if(in_array($atts[$i],$students))
{
$students->Reason='1';
}
else
{
$students->Reason='0';
}
}
echo '<pre>',print_r($students,1),'</pre>';
Here I am unable to update student array with "reason" values.
If you just want to compare student_id from array1 with student_id from array2, and set Reason in array2 if they correspond to each other, use this :
foreach ($array1 as $key1 => $value1) {
foreach ($array2 as $key2 => $value2) {
if ($value1['student_id'] == $value2['student_id']) {
$array2[$key2]['Reason'] = 1;
} else if ($array2[$key2]['Reason'] != 1) {
$array2[$key2]['Reason'] = 0;
}
}
}
Here's a quickie for the pros:
How do I display Value 1, 2, 3 etc as it's in it's third array?
$meta_boxes = array
(
"checkbox" => array
(
"name" => "checkbox",
"title" => "",
"description" => "This is an example of a checkbox field.",
"type" => "checkbox",
"rows" => "",
"width" => "",
"options" => array
(
"1" => "Value 1",
"2" => "Value 2",
"3" => "Value 3"
)
),
$str = '';
foreach($meta_boxes['checkbox']['options'] as $k => $v) {
$str .= $v . "\n";
}
$meta_boxes['checkbox']['options']['1'] will give you the string "Value 1" from the array, and then you can do whatever you want with that value.
You should now be able to figure out how to access the other two.