I am trying to sort the following arrays.
Array(s)
$fruits = array(
'mango',
'mango red',
'mango yellow',
'orange',
'banana',
'apple',
'apple red',
'apple green',
);
What I have done:
$data = array_flip( $fruits ); // flip array
$data = array_fill_keys( array_keys( array_flip( $data ) ), 'array(),' ); // fill array value: "array(),"
print_r( $data );
I want this result:
$fruits = array(
'mango' => array(
'red' => array(),
'yellow' => array(),
),
'orange' => array(),
'banana' => array(),
'apple' => array(
'red' => array(),
'green' => array(),
),
);
Does anybody know how to do this?
Hope you can understand the question. Thank you in advance.
Loop through the array, and split the string. Then recursively create nested arrays.
$result = array();
foreach ($fruits as $f) {
$f_array = explode(' ', $f);
$start = &$result;
foreach ($f_array as $word) {
if (!isset($start[$word])) {
$start[$word] = array();
}
$start = &$start[$word];
}
}
var_dump($result);
DEMO
Use the following approach(for your current array):
$result = [];
foreach ($fruits as $fruit) {
$parts = explode(' ', $fruit);
if (count($parts) == 1) {
$result[$fruit] = [];
} elseif (isset($result[$parts[0]])) {
$result[$parts[0]][$parts[1]] = [];
}
}
print_r($result);
Related
I need to match all "keywords" in a multidimesional array:
$array = array(
'green' => 'keyword',
'orange',
'keyword',
'black' => array(
'purple' => 'text',
'brown',
'pink' => 'keyword'
),
'white' => array(
'red',
'yellow' => 'keyword',
'blue'
),
'violet',
'gray'
);
Then I would like to access the match results like:
$matches[0][0]
$matches[2]
$matches[3][2]
....
What should I use? I tried with array_filter but doesn't work.. also it might have to be recursive
function findInArray($array){
$array = array_filter($array, function($array){
return ($array == 'keyword');
});
return $array;
}
You can did the thing by using array_filter.
Online check 3v4l.org
$arr = array();
$str = 'keyword';
$arr[] = array_filter($array, function($var) use ($str) {
global $arr;
if(is_array($var)){
$arr[] = array_filter($var, function($var2) use ($str) {
return preg_match("/$str/i", $var2);
});
}else{
return preg_match("/$str/i", $var);
}
});
function getL2Keys($array){
$result = array();
foreach($array as $sub) {
$result = array_merge($result, $sub);
}
return $result;
}
$arr = getL2Keys($arr);
Result:
Array
(
[pink] => keyword
[yellow] => keyword
[green] => keyword
[0] => keyword
)
I have two arrays (below). Is it possible to convert them into json string?
Array
(
[0] => size
[1] => color
)
Array
(
[0] => L
[1] => Black
)
Output structure should be:
[
{"name":"size","value":"L"},
{"name":"color","value":"Black"}
]
Thanks!
Sure:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
This gives you
[{"name":"size","value":"L"},{"name":"color","value":"Black"}]
this here should work:
$json = json_encode( array_combine( $array1, $array2 ) );
Something like this should work just how you want:
<?php
$keys = array("size", "color");
$values = array("L", "Black");
$array = array();
foreach ($keys as $i => $key) {
$array[] = array(
"name" => $key,
"value" => $values[$i]
);
}
$json = json_encode($array);
var_dump($json);
//string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$result = array_combine($array1 , $array2);
$json = array();
foreach($result as $key => $val){
$json[] = array('name' => $key, 'value' => $value);
}
$json = json_encode($json);
I think you are looking for this:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
{
$array3[]=array($array1[$i]=>$array2[$i]);
}
echo json_encode($array3);
?>
Output:
[{"size":"L"},{"color":"Black"}]
I have an array that looks something like this:
$array = array(
array('Field1' => 'red', 'Field2' => 'green', 'Field3' => 'blue'),
array('Field1' => 'pink', 'Field2' => 'pinkish', 'Field3' => 'barbiecolor'),
array('Field1' => 'red', 'Field2' => 'blue', ' Field3' => 'orange')
);
And I want to check this by the given values:
$searchBy = array('Field1' => 'red', 'Field2' => 'blue');
What I want to achieve, is to return the parent array that has all associative key & value pairs matched. I've tried in_array() but it doesn't work..
array_filter may be better for this:
$matches = array_filter($array,function($a) use ($searchBy) {
foreach($searchBy as $k=>$v) {
if( $a[$k] != $v) return false;
}
return true;
});
You can try:
$find = array_filter($array, function ($a) use($searchBy) {
return array_intersect_assoc($searchBy, $a) == $searchBy;
});
See Live Demo
Old School Version
$find = find($searchBy, $array);
print_r($find);
// Function used
function find($needle, $haystack) {
$r = array();
foreach ( $haystack as $k => $a ) {
array_intersect_assoc($needle, $a) == $needle and $r[$k] = $a;
}
return $r;
}
Old School Demo
I have a maybe stupid question?
I have three arrays. And I want to get different values from the first and third array. I created the following code but the returned values are wrong.
function ec($str){
echo $str.'<br>';
}
$arr1 = array( array(
'letter' => 'A',
'number' => '1'
),
array(
'letter' => 'B',
'number' => '2'
),
array(
'letter' => 'C',
'number' => '3'
)
);
$arr2 = array( array(
'letter' => 'A',
'number' => '1'
),
array(
'letter' => 'B',
'number' => '2'
)
);
$arr3 = array( array(
'letter' => 'D',
'number' => '4'
),
array(
'letter' => 'E',
'number' => '5'
)
);
$mergeArr = array_merge($arr1,$arr3);
foreach ($mergeArr as $kMerge => $vMerge){
foreach ($arr2 as $val2){
if($val2['letter'] != $mergeArr[$kMerge]['letter']){
ec($mergeArr[$kMerge]['letter']);
}
}
}
The result of this code is:
A
B
C
C
D
D
E
E
The result I want:
C
D
E
Thanks in advance.
Based on the result you are looking for, this should do it:
$mergeArr = array_merge($arr1,$arr3);
$res = array_diff_assoc($mergeArr, $arr2);
var_dump($res);
See the snippet on codepad.
Try this instead of your foreach's:
$diff = array_diff($mergeArr, $arr2);
foreach( $diff as $d_k => $d_v ) {
ec($d_v['letter']);
}
If I understand what you are trying to do correctly, this function should do the job:
function find_unique_entries () {
$found = $repeated = array();
$args = func_get_args();
$key = array_shift($args);
foreach ($args as $arg) {
if (!is_array($arg)) return FALSE; // all arguments muct be arrays
foreach ($arg as $inner) {
if (!isset($inner[$key])) continue;
if (!in_array($inner[$key], $found)) {
$found[] = $inner[$key];
} else {
$repeated[] = $inner[$key];
}
}
}
return array_diff($found, $repeated);
}
Pass the key you are searching to the first arguments, then as many arrays as you like in the subsequent arguments. Returns an array of results or FALSE on error.
So your usage line would be:
$result = find_unique_entries('letter', $arr1, $arr2, $arr3);
See it working
How can I search for a key in an array that contains more arrays.
For example I would like to search for "key" in "arr" and return this:
arr["some_inner_array"]["another_array_possible"][key"]
array_key_exists can tell me if it exists, but of course what I really need in the value...
I hope my question is clear...
EDIT:
based on the answer below, I managed to do a recursive function for that:
function look_in_array ( $array, $key ) {
if ( isset($array[$key]) )
return $array[$key];
foreach ($array as $item) {
if (is_array($item)) {
$value = look_in_array ($item,$key);
if ($value)
return $value;
}
}
}
This function should work:
function array_key_exists_recursive($searchKey, $array)
{
$result = false;
foreach($array as $key => $value)
{
if(is_array($array[$key]))
{
$result = array_key_exists_recursive($searchKey, $array[$key]);
}
else if(array_key_exists($searchKey, $array))
{
$result = $array[$searchKey];
}
if($result)
break;
}
return $result;
}
Exmaple:
$array = array( "a" => array("b" => "1", "c" => "2") );
var_dump(array_key_exists_recursive("c", $array)); //Result: 2
You could just ask this:
isset(arr["some_inner_array"]["another_array_possible"]["key"])
Would this work for you? Otherwise maybe explaning a bit better about what you're trying to accomplish would help us help you :)
You need to iterate over all elements in the first arrays and then use array_key_exists():
foreach($arr as $inner1) {
foreach($inner1 as $inner2) {
if array_key_exists($inner2, $key) {
echo $inner2[$key];
break 2; // if you only want the first match
}
}
}
Try this:
/**
* #param $path array containing path
* #param $array search array
* #return element matching path or null
*/
function arr_search($path, &$array){
$tmp = &$array;
for($i = 0; $i < count($path); $i++){
if(!isset($tmp[$path[$i]])) return null;
$tmp = &$tmp[$path[$i]];
}
return $tmp;
}
$arr = array(
'a' => array(
'b' => array(
'c' => 'abc',
),
'd' => array('ad'),
),
10 => array(100, 200, 300),
);
var_dump(arr_search(array('a', 'b', 'c'), $arr));
var_dump(arr_search(array('a', 'd'), $arr));
var_dump(arr_search(array(10, 100), $arr));
var_dump(arr_search(array(10, 1), $arr));
// EDIT previous example was wrong, so here is new one :)
function arr_search($key, $array){
$values = array();
if(array_key_exists($key, $array)) $values[] = $array[$key];
$stack = array_values($array);
while($tmp = array_pop($stack)){
if(is_array($tmp)){
foreach($tmp as &$v){
array_push($stack, $v);
}
if(array_key_exists($key, $tmp)){
$values[] = $tmp[$key];
}
}
}
return $values;
}
$arr = array(
'a' => array(
'b' => array(
'c' => 'abc',
),
'd' => array('ad'),
),
'e' => array(
'a' => array(
'b' => 'abc',
),
'b' => array('xyz'),
),
10 => array(100, 200, 300),
);
var_dump(arr_search('b', $arr));
var_dump(arr_search(0, $arr));