To save on typing out the key name for every single array, I want to be able to build lists like..
$lists = array (
0 => array ('A', 'B', 'C', 'D', 'E');
1 => array ('A', 'B', 'C', 'D', 'E');
2 => array ('A', 'B', 'C', 'D', 'E');
)
.. and then assign the same key names to all them (either before or after)..
Key1, Key2, Key3, Key4, Key5
.. so when they're called, I can do something like..
foreach($lists as $list) {
showList($list);
}
.. and then within the showList() function, I can call the 5 keys by the key name.
The function I have set no problem, but it's assigning the key names that I'm not sure how to do. Sorry if my terminology isn't accurate, but hopefully I explained it well enough.
array_combine will make an associative array from an array of keys and an array of values.
$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
foreach ($lists as $list) {
showList(array_combine($keys, $list));
}
If you want to modify $lists permanently, you can do:
foreach ($lists as &$list) {
$list = array_combine($keys, $list);
}
The reference variable &$list makes this replace the elements in place.
Try this :
<?php
$keys = array('Key1', 'Key2', 'Key3', 'Key4', 'Key5');
$lists = array (
array ('A', 'B', 'C', 'D', 'E'),
array ('A', 'B', 'C', 'D', 'E'),
array ('A', 'B', 'C', 'D', 'E')
);
function showList($list){
global $keys;
return array_combine($keys, $list);
}
$output = array_map("showList", $lists);
echo "<pre>";
print_r($output);
?>
Result:
Array
(
[0] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
[1] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
[2] => Array
(
[Key1] => A
[Key2] => B
[Key3] => C
[Key4] => D
[Key5] => E
)
)
Related
I have array something like:
Array (
[0]=>{"a":"b", "c":"d", "h":"e"}
[1]=>{"a":"b", "f":"g"}
)
How i can removing duplicates here? I'm trying array_unique, but it's not working.
Expected result:
Array (
[0]=>{"a":"b", "c":"d", "h":"e"}
[1]=>{"f":"g"}
)
In this scenario, you need to be careful with duplicate keys yet different values. So match to remove duplicates has to be on combination of both key and value.
To do this, we can collect all keys in an array say $map and have all values visited for this keys inside that key array.
Now, we can just do an in_array check to get hold of whether we got some key-value pair like this before or not.
Snippet:
$arr = [
[
'a' => 'b',
'c' => 'd',
'h' => 'e'
],
[
'a' => 'b',
'f' => 'g',
'c' => 'f'
],
[
'a' => 'd',
'c' => 'd'
]
];
$map = [];
foreach($arr as $index => $data){
foreach($data as $key => $value){
if(!isset($map[$key])) $map[$key] = [];
if(in_array($value,$map[$key])) unset($arr[$index][$key]);
else $map[$key][] = $value;
}
}
print_r($arr);
Demo: https://3v4l.org/RWcMu
You can do it with array_diff() and unset() functions. But, you need to decode this JSON values firstly:
foreach($ar as $in => &$js){
$ar[$in] = json_decode($js,true);
}
After this $ar has a view like:
Array
(
[0] => Array
(
[a] => b
[c] => d
[h] => e
)
[1] => Array
(
[a] => b
[f] => g
)
)
Here you can apply array_diff() function:
$diff = array_diff($ar[1],array_diff($ar[1],$ar[0]));
It will collect duplicates from [1] index in [0]:
Array
(
[a] => b
)
Now you can unset these values from [1] index:
foreach($diff as $ind=>$uns){
unset($ar[1][$ind]);
}
And finally you can change JSON view back:
foreach($ar as $in=>&$js){
$ar[$in] = json_encode($js);
}
Result would be:
Array
(
[0] => {"a":"b","c":"d","h":"e"}
[1] => {"f":"g"}
)
Demo
If input elements are objects, then use this loop at the first step:
foreach($ar as $in=>&$obj){
$ar[$in] = (array)$obj;
}
Demo
I show my example of diff between values in arrays, sometimes doesn't work corectly.
$fields = array(
'1x1' => 'k',
'1x2' => 'B',
'1x3' => 'c',
'2x1' => 'd',
'2x2' => 'x',
'2x3' => 'Y',
'3x1' => 'b',
'3x2' => 'e',
'3x3' => 'f'
);
print_r($fields);
$answer = array(
'a',
'b',
'c',
'd',
'x',
'y',
'z',
'e',
'f'
);
print_r($answer);
echo '<hr />DIFF:<br />';
print_r(array_diff($fields, $answer));
?>
Results is:
(
[1x1] => k
[1x2] => B
[2x3] => Y
)
But should be:
(
[1x1] => k
[1x2] => B
[2x3] => Y
[3x1] => b
)
Why for PHP b is equal with z?
How to repair this?
This is working correct. According to array_diff() documentation:
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
Another important info from documentation:
Two elements are considered equal if and only if (string) $elem1 ===
(string) $elem2. In words: when the string representation is the same.
So in $answers array there are no k, B, Y elements of $fields array.
The method isn't wrong, compare the 2 lists, they both contain b
see you put 'b' into both the $answer and the $fields array .
so that's why it gives u such output .
I am trying to find a way to transform a string type variable into an array type variable. To be more precise, what i am looking for is the change this (example):
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
note that this is not a json-formatted string.
into this:
$v = ['1', 'a', ['2', 'b', ['3'], 'c']];
Note the double-quotes in the first example, $v is a string, not an array, which is the desired effect.
Simple solution using str_replace(to prepare for decoding) and json_decode functions:
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$converted = json_decode(str_replace("'",'"',$v));
print_r($converted);
The output:
Array
(
[0] => 1
[1] => a
[2] => Array
(
[0] => 2
[1] => b
[2] => Array
(
[0] => 3
)
[3] => c
)
)
$v = "['1', 'a', ['2', 'b', ['3'], 'c']]";
eval("\$v = $v;");
var_dump($v);
PS: make sure $v string doesn't contain unexpected code.
This should work:
$json = "['1', 'a', ['2', 'b', ['3'], 'c']]";
$json = str_replace("'",'"',$json);
$result_array = json_decode($json); // This is your array
I want to loop through an array and get each element to pass as parameters to a constructor.
here is my example
[user_by_province] => Array
(
[label] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[count] => Array
(
[0] => 2
[1] => 1
[2] => 1
[3] => 1
[4] => 7
[5] => 1
)
)
Here is the constructor:
$pc = new C_PhpChartX(array(array('a','2'),
array('b','1'),
array('c','1'),
array('d','1'),
array('e','7'),
array('f','1')));
so how can i do that with php thanks for any help, may we can do that with array_map or no? thanks for any help
As you suggested array_map with multiple arguments could be a good solution.
<?php
$userByProvince = array(
'label' => array('a', 'b', 'c', 'd', 'e', 'f'),
'count' => array('1', '2', '3', '4', '5', '6'),
);
function combine($arg1, $arg2)
{
return array($arg1, $arg2);
}
$arguments = array_map('combine', $userByProvince['label'], $userByProvince['count']);
$pc = new C_PhpChartX($arguments);
If you are using PHP 5.3 you can even substitute the function with a lambda expression to make the code more compact (see docs).
It's easier to use array_combine.
you can do something like this:
$my_array=array("user_by_province"=>array("label"=>array('a','b','c','d','e','f'),"count"=>array(2,1,1,1,7,1)));
$new_array=array();
for($i=0;$i< count($my_array['user_by_province']['label']);$i++){
$new_values=array();
array_push($new_values,$my_array['user_by_province']['label'][$i],$my_array['user_by_province']['count'][$i]);
array_push($new_array,$new_values);
}
supposed your given array is ordered and has the same amount of data, i.e. pairs:
loop over your data:
$input = array("user_by_province"
=> array("label" => array('a', 'b', 'c'),
"count" => array(1, 2, 3)));
$combined = array();
for($i = 0; $i < count($input['user_by_province']['label'] && $i < count($input['user_by_province']['count']; $i++)
{
$combined[] = array($input['user_by_province']['label'][$i], $input['user_by_province']['count'][$i]);
}
$pc = new C_PhpChartX($combined);
I have two arrays and want to find the first match for either of arrayTwos values in arrayOne.
arrayOne ( [0] = C [1] = A [2] = B [3] = D [4] = B [5] = C)
and
arrayTwo ( [0] = A [1] = B [2] = C )
With these values I would want to return the value "C" as it is the first value in arrayTwo to appear in arrayOne.
I'm thinking I could use for loops and if statements to run through but re there any functions in PHP I could use to simplify this?
Use array_search
$keys = array_search($second_array, $first_array);
Ref : http://in3.php.net/array_search
array_search
$valuekeys = array_search($secondarray, $arrayone);
use array_intersect
$arrayOne = array('C', 'A', 'B', 'D', 'B', 'C');
$arrayTwo = array('A', 'C');
$result = array_intersect($arrayOne , $arrayTwo);
echo $result[0];
Use array_intersect. This will do the job. http://www.php.net/manual/en/function.array-intersect.php Note the difference between using array_intersect($array1, $array2) and array_intersect($array2, $array1)
You can use array_intersect():
$arr1 = array( 0 => 'C', 1 => 'A', 2 => 'B', 3 => 'D', 4 => 'B', 5 => 'C');
$arr2 = array( 0 => 'A', 1 => 'B', '2' => 'C' );
$arr3 = array_intersect($arr1,$arr2);
var_dump($arr3[0]);
string(1) "C"