PHP - Get the value by key in a multi-dimension array - php

I have a multi-dimension array like:
$fields =
Array (
[1] => Array
(
[field_special_features5_value] => Special Function 5
)
[2] => Array
(
[field_special_features6_value] => Special Function 6
)
[3] => Array
(
[field_opticalzoom_value] => Optical Zoom
)
)
I want to get the value by key, I tried the code below but not work
$tmp = array_search('field_special_features5_value' , $fields);
echo $tmp;
How can I get the value Special Function 5 of the key field_special_features5_value?
Thanks

print $fields[1]['field_special_features5_value'];
or if you don't know at which index your array is, something like this:
function GetKey($key, $search)
{
foreach ($search as $array)
{
if (array_key_exists($key, $array))
{
return $array[$key];
}
}
return false;
}
$tmp = GetKey('field_special_features5_value' , $fields);
echo $tmp;

If you know where it is located in the $fields array, try :
$value = $fields[1]['field_special_features5_value'];
If not, try :
function getSubkey($key,$inArray)
{
for ($fields as $field)
{
$keys = array_keys($field);
if (isset($keys[$key])) return $keys[$key];
}
return NULL;
}
And use it like this :
<?php
$value = getSubkey("field_special_features5_value",$fields);
?>

You need to search recursive:
function array_search_recursive(array $array, $key) {
foreach ($array as $k => $v) {
if (is_array($v)) {
if($found = array_search_recursive($v, $key)){
return $found;
}
} elseif ($k == $key) {
return $v;
} else {
return false;
}
}
}
$result = array_search_recursive($fields, 'field_special_features5_value');

Your problem is that you have a top-level index first before you can search you array. So to access that value you need to do this:
$tmp = $fields[1]['field_special_features5_value'];

You can do it with recursive function like this
<?php
function multi_array_key_exists($needle, $haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$key) {
return $key;
}
if (is_array($value)) {
if(multi_array_key_exists($needle, $value)) {
return multi_array_key_exists($needle, $value);
}
}
}
return false;
}
?>

Related

how to scan null index in array, and print it with a new value in php?

<?php
function tambah_penumpang($daftar_penumpang, $penumpang_baru){
if(empty($namaArray)==true){
$daftar_penumpang[]=$penumpang_baru;
return $daftar_penumpang;
}else{
for($i=0; $i<count($daftar_penumpang); $i++){
if($daftar_penumpang[$i]== null){
$daftar_penumpang[$i]=$penumpang_baru;
return $daftar_penumpang;
}else{
$daftar_penumpang[] = $penumpang_baru;
return $daftar_penumpang;
}
}
}
}
$daftar_penumpang =["sandhika",null,"carl","keith"];
print_r(tambah_penumpang($daftar_penumpang,"anggoro"))."<br>"
?>
And this are the result: (i want that anggoro name in null's index)
Array (
[0] => sandhika
[1] =>
[2] => carl
[3] => keith
[4] => anggoro
)
as I'm not familiar with your naming convention , i've made a global example using array_walk as follows:
$daftar_penumpang =["sandhika",null,"carl","keith"];
array_walk($daftar_penumpang, function($v, $k, $replacement) use (&$daftar_penumpang) {
if ($v == null) {
$daftar_penumpang[$k] = $replacement;
}
}, 'anggoro');
print_r($daftar_penumpang);
live example: https://3v4l.org/vVnSq
for your case :
$daftar_penumpang =["sandhika",null,"carl","keith"];
function tambah_penumpang($daftar_penumpang, $penumpang_baru) {
array_walk($daftar_penumpang, function($v, $k, $replacement) use (&$daftar_penumpang) {
if ($v == null) {
$daftar_penumpang[$k] = $replacement;
}
}, $penumpang_baru);
return $daftar_penumpang;
}
print_r(tambah_penumpang($daftar_penumpang, 'anggoro'));
this will output:
Array ( [0] => sandhika [1] => anggoro [2] => carl [3] => keith )
Update
using for loop :
your code issue is that you will never ever get into the for loop because it is in else condition , and while the $namaArray is alway empty, so you will never go through the loop , so i've removed this check and prepared this looping to show you how to replace null values using for loop
function tambah_penumpang($daftar_penumpang, $penumpang_baru)
{
$tmpArray = [];
for ($i=0; $i < count($daftar_penumpang); $i++) {
if ($daftar_penumpang[$i]== null) {
$tmpArray[$i] = $penumpang_baru;
} else {
$tmpArray[] = $daftar_penumpang[$i];
}
}
return $tmpArray;
}
$daftar_penumpang =["sandhika",null,"carl","keith"];
print_r(tambah_penumpang($daftar_penumpang,"anggoro"));
Try with this function :
<?php
function tambah_penumpang($daftar_penumpang, $penumpang_baru){
$datas = [];
for($i = 0; $i < count($daftar_penumpang); $i++) {
$item = $daftar_penumpang[$i];
if($item === null) {
$item = $penumpang_baru;
}
$datas[$i] = $item;
}
return $datas;
}
$daftar_penumpang =["sandhika",null,"carl","keith"];
print_r(tambah_penumpang($daftar_penumpang,"anggoro"))."<br>";

PHP move duplicates in recursive array

I building a translation form that is build using a array filled with the translation keys, to keys are however often duplicated. As the form is builded in group i want to move the duplicates to the $translatables['global']
Note that what you're seeing in the image below is already placed in $translatables['modules']['Module_{{ModuleName}}']
As you can see in the image below, some fields are duplicates. those needs to be moved. The duplicates can be placed accross multiple elements.
I edit for the duplicate message: It ain't, its a question to move those values not to filter them (and keep 1 remaining), they need to be placed under a global section.
I solved it myself
class Tools_Array
{
public static function find_duplicates_recursive(&$array, $remove = false)
{
$duplicates = array();
$valueCounts = array_count_values(self::array_values_recursive($array));
foreach ($valueCounts as $key => $value) {
if ($value > 1)
{
$duplicates[] = $key;
}
}
if ($remove) {
foreach ($duplicates as $duplicate)
{
$array = self::remove_values_recursive($array, $duplicate);
}
}
return $duplicates;
}
public static function array_values_recursive($array)
{
$arr2 = array();
foreach ($array as $key => $value)
{
if(is_array($value))
{
$arr2 = array_merge(array_values_recursive($value), $arr2);
}else{
$arr2[] = $value;
}
}
return $arr2;
}
public static function remove_values_recursive($array, $needle)
{
foreach ($array as $key => $value)
{
if(is_array($value))
{
$array[$key] = self::remove_values_recursive($value, $needle);
}else{
if ($value == $needle)
{
unset($array[$key]);
}
}
}
return $array;
}
}
Then i can filter it with:
$duplicates = Tools_Array::find_duplicates_recursive($translatables, true);
$translatables['globaal'] = array_merge($translatables['globaal'], $duplicates);

PHP search multidimensional array with more than one result?

I found a way to search my multidimensional array and output the result and it works, however it only finds the first match and stops. If I have more than one match in the array I want to be able to show them all.
My array looks like this (the first layer of keys goes from 0, 1, 2 etc):
Array
(
[0] => Array
(
[mydevice] => blahblah
[ipadd] => 10.10.10.209
[portnum] => 16040
)
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
$myoutput = searcharray($ptn2, mydevice, $newresult);
I can then echo the results using something like $newresult[$myoutput][mydevice].
However if I have more than one entry in the array with a matching data in the 'mydevice' key it doesn't return them (just the first one).
That is because return breaks the function. You could use something like this:
function searcharray($value, $key, $array) {
$result = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$result[] = $k;
}
}
return $result;
}
Now you will always get an array as result - empty if nothing was found. You can work with this like this e.g.
$mydevicekeys = searcharray($ptn2, "mydevice", $newresult);
foreach ($mydevicekeys as $mydevicekey) {
// work with $newresult[ $mydevicekey ]["mydevice"]
}
So add the results to an array :)
function searcharray($value, $key, $array) {
$res = array();
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
$res[] = $key;
}
}
return $res;
}

fetch value in multidimensional associative array?

I have a SESSION array $_SESSION['cart']
for example it has value as
Array
(
[0] =>
[1] => Array
(
[item_id] => 1420
[item_qty] => 1
)
[2] => Array
(
[item_id] => 1522
[item_qty] => 1
)
)
Now let's say I have item_id = 1420
now I want to increase the item_qty for item_id = 1420 and also I have to set it in that SESSION array.
What I tried it :
foreach($_SESSION['Cartquantity'] as $key => $d)
{
if(isset($d)) {
if($d['item_id'] == $_GET['item_id'])
{
$d['item_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
It's not working ?
You're iterating over $_SESSION['Cartquantity'] but have told us that the array is stored in $_SESSION['cart'].
Also, this:
$d['tem_quntity'] = $d['item_quantity']+1;
Should be:
$d['item_qty'] = $d['item_qty']+1;
Finally, you'll need to make $d a reference by prepending an ampersand (&) to it in the foreach condition.
foreach($_SESSION['cart'] as $key => &$d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['item_qty'] = $d['item_qty']+1;
}
}
else{
}
}
Use reference &$d
foreach($_SESSION['Cartquantity'] as $key => &$d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['tem_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
or
foreach($_SESSION['Cartquantity'] as $key => $d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$_SESSION['Cartquantity'][$key]['item_quntity'] = $d['item_quantity']+1;
}
}
else{
}
}
change this
$d['tem_quntity'] = $d['item_quantity']+1;
to
$d['item_qty'] = $d['item_qty']+1;
you can call by
foreach ($_SESSION['Cartquantity'] as $value))
{
if(isset($value))
{
if($value['item_id'] == $_GET['item_id'])
{
$value['item_quntity'] = $value['item_quantity']+1;
}
}
else
{
}
}
Try to check for !empty($array)
if(!empty($d))
because it array so you need to check for if its do not have any elements inside of it.
If you want to know if the array is defined , then use isset($d).
If you want to know if a particular key is defined, use isset($d['item_id']).
If you want to know if an array has not empty and has key value pairs , use !empty($d).
use it:
foreach($_SESSION['cart'] as $key => $d)
{
if($d) {
if($d['item_id'] == $_GET['item_id'])
{
$d['tem_quntity'] = $d['item_qty']+1;
}
}
else{
}
}
foreach($_SESSION['cart'] as $key=>$val)
{
foreach($val as $subK)
{
if($_GET["item_id"]==$subk["item_id"])
{
$_SESSION['cart'][$key]["item_id"]=$_SESSION['cart'][$key]["item_quantity"]+1;
}
}
}

return row of array where key=value in multi dimentional array

array:
array(
['name'=>'kevin','value'=>'10'],
['name'=>'sam','value'=>'20']
);
how can i return value where name='sam' for example ?
and what how can i do it in even deeper array
array(
[0]=>array( 'inputs'=>
array(['name'=>'kevin','value'=>'10'],['name'=>'sam','value'=>'20']
),
[1]=>array( 'inputs'=>
array(['name'=>'kim','value'=>'10'],['name'=>'kirki','value'=>'20']
)
);
you need a recursive array_search - all answers above handle an exact amount of depth (in this case 2) only.
something like
function recursive_array_search($needle,$haystack) {
foreach ($haystack as $key=>$value) {
if ($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $value['value'];
}
}
return false;
}
recursive_array_search('sam', $start_array);
$arr = array(
array("name"=>"A","info"=>"one"),
array("name"=>"B","info"=>"two"),
array("name"=>"C","info"=>"three")
);
foreach($arr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
In Deep Level
$arr = array(
array("input"=>array(
"name"=>"A",
"info"=>"one"
)),
array("input"=>array(
"name"=>"B",
"info"=>"Two"
))
);
foreach($arr as $subarr){ // First foreach iterate through arrays and next foreach iterate through values of each sub array
foreach($subarr as $v){
if ($v['name']==="A"){
echo $v['info'];
}
}
}
for($i=0;$i<count($array);$i++)
{
if($array['name']=="sam")
{
echo $array['value'];
}
}
and for next array you can do like this....
for($i=0;$i<count($array);$i++)
{
for($j=0;$j<count($array[$i]['inputs']);$j++)
{
if($array[$i]['inputs'][$j]['name']=="sam")
{
echo $array[$i]['inputs'][$j]['info'];
}
}
}
$new_array = array();
foreach ($old_array as $value) {
$new_array[$value['name']] = $value['value'];
}
var_dump($new_array['kevin']); // prints 10

Categories