I have an array, similar to the following:
$array = [
['file' => 1, 'status' => 'pending'],
['file' => 2, 'status' => 'pending'],
];
What I want to do is to replace the statuspart, where the file is 1
I'm not sure if i can do this in a simple array, or using an in-built array_ method
I have something liek the following so far:
$data = [];
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$data['status'] = 'updated';
}
}
You're close, but as $data is array of arrays, you need to provide $arr as top-level key and even get rid of second array:
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$array[$arr]['status'] = 'updated';
}
}
This should give you an idea of how to tackle that.
if ($array[0]['file'] == 1) {
$array[0]['whatever'] = $array[0]['status'];
unset($array[0]['status']);
}
The 0 can ofcourse be changed by i in a loop if you wish to cycle through the entire array.
Related
I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);
I've two array, something like this,
form_field_combined = ["920" => "920", "921" => "921", "922" =>"922", "923" => "923", "924" => "924", "925" => "925", "926" => "926"];
And next array is something like this,
$values = ["920"=>"Answer", "924" => "Option", "926"=>"Something Awesome"];
Note: The length of second array $values is always be equal to or less than the first array $form_field_combined .
Now What I want to achieve is, a combined array from these two array, so that it would look something like this.
$new_array = ["920"=>"Answer", "921"=>"", "922" => "", "923"=>"", "924" => "Option", "925" => "", "926"=>"Something Awesome"];
My solution would be to use array_map something like this:
$form_data_values = [];
$all_fields = array_map(function ($each, $key) use ($values, $form_data_values) {
array_map(function ($each_value, $each_key) use ($each, $key, $values, $form_data_values) {
if (in_array($each, $values)) {
array_push($form_data_values, [$key => $values[$each]]);
} else {
array_push($form_data_values, [$key => ""]);
}
dd($form_data_values); // The values are as expected and being preserved here..
}, $values, $form_data_values);
dd($form_data_values); // The value is lost now, and is blank.
}, $values, array_keys($form_field_combined));
I want that $form_data_values array to be preserved, so that I could use that elsewhere, which in my case not working.
Or You could see the expected result and propose any other way around. Thank You
This will do it.
$result = array();
foreach ($form_field_combined as $key => $val) {
$result[$key] = !empty($values[$key]) ? $values[$key] : "";
}
For preserving 0 use isset
$result = array();
foreach ($form_field_combined as $key => $val) {
$result[$key] = isset($values[$key]) ? $values[$key] : "";
}
I have a PHP array that I am trying to split into 2 different arrays. I am trying to pull out any values that contain the word "hidden". So one array would contain all the values that do not contain the word "hidden". The other array would contain all the values that do contain the word "hidden". I just can't figure out how to do it though.
The original array is coming from a form post that contains keys and values from a bunch of check boxes and hidden inputs. so the actual post value looks something like this:
Group1 => Array([0] => item1,[1] => item2hidden,[2] => item3,[3] => item4,[4] => item5hidden)
so to simplify it:
$myArray = Array(item1, item2hidden, item3, item4, item5hidden)
final output
$arr1 = (item1, item3, item4)
$arr2 = (item2hidden, item5hidden)
Anyone know how to do something like this?
You can use array_filter() function:
$myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
$arr1 = array_filter($myArray, function($v) { return strpos($v, 'hidden') === false; });
$arr2 = array_diff($myArray, $arr1);
This should do the trick:
$myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
$secondaryArray = array();
foreach ($myArray as $key => $value) {
if (strpos($value, "hidden") !== false) {
$secondaryArray[] = $value;
unset($myArray[$key]);
}
}
It moves all the entries that contain "hidden" from the $myArray to $secondaryArray.
Note: It's case sensitive
$myArray = Array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
$arr1 = array();
$arr2 = array();
foreach ($myArray as $item) {
if (strpos($item, "hidden") !== false) {
$arr1[] = $item;
} else {
$arr2[] = $item;
}
}
This solution checks if 'hidden' present at current item, if no, move to $arr1 else to $arr2
You can use array_filter:
function filtreHiddens($e) {
if (isset($e['hidden']) && $e['hidden']) return true;
else return false;
}
function filtreNotHiddens($e) {
if (isset($e['hidden']) && !$e['hidden']) return true;
else return false;
}
$arrayToFiltre = array(
array('hidden' => true, 'someKey' => 'someVal'),
array('hidden' => false, 'someKey1' => 'someVal1'),
array('hidden' => true, 'someKey2' => 'someVal3'),
);
$hidden = array_filter($arrayToFiltre, 'filtreHiddens');
$notHidden = array_filter($arrayToFiltre, 'filtreNotHiddens');
print_r($hidden);
print_r($notHidden);
Maybe it's just me, but I would go for the clarity of regular expressions...
foreach($myArray as $item) {
if (preg_match("/hidden$/i", $item)) {
array_push($arr2, $item);
} else {
array_push($arr1, $item);
}
}
I'm sure this has been asked before, but I can't seem to find the answer.
To that end, I have an array that looks like this:
Array
(
[0] => Array
(
[status] => active
[sid] => 1
)
[1] => Array
(
[status] => expired
[sid] => 2
)
)
What I'd like to be able to do is type $arrayName["active"] and it return the SID code. I will be using this like a dictionary object of sorts. It's like I need to reindex the array so that it is the key/value pair that I need. I was just wondering if there was an easier way to do it.
You should convert your nested arrays into a single associative array. Something like this should take your example and turn it into an associative array:
$assoc_array = array();
foreach( $example_array as $values ) {
$assoc_array[$values["status"]] = $values["sid"];
}
You can then access the sid for a given status by using $assoc_array["expired"] (returns 2)
After seeing the others' solutions, I realize this might be bit of an overkill, but I'm still just gonna throw it out there:
$foo = array(
array('status' => 'active', 'sid' => 1),
array('status' => 'expired', 'sid' => 2),
);
// Get all the 'status' elements of each subarray
$keys = array_map(function($element) {
return $element['status'];
}, $foo);
// Get all the 'sid' elements of each subarray
$values = array_map(function($element) {
return $element['sid'];
}, $foo);
// Combine them into a single array, with keys from one and values from another
$bar = array_combine($keys, $values);
print_r($bar);
Which prints:
Array
(
[active] => 1
[expired] => 2
)
Manual pages:
array_map()
array_keys()
array_values()
array_combine()
Anonymous functions
You can use this function:
function findActive($my_array){
foreach($my_array as $array){
foreach($array as $val){
if($val['status']==='active'){
return $val['sid'];
}
}
}
return false;
}
access it via a loop or directly.
if($arrayName[0]['status'] == "active") {
echo $arrayName[0]['sid'];
}
If you want to check all the SIDs
foreach($arrayName as $item) {
if($item['status'] == "active") {
echo $item['sid'];
}
}
A more direct approach is just putting the loop in a function and return an array of all active session IDs
$sidArr = array();
foreach($yourArr as $val) {
if("active" == $val["status"]) {
array_push($sidArr, $val["sid"]);
}
}
reindex would be the best
$arrayName = array()
foreach ($data_array as $data)
$arrayName[$data['status']]=$data['sid'];
Or use a function
function get_sid($status)
{
global $data_array;
foreach ($data_array as $data) {
if ($data['status']==$status)
return $data['sid'];
}
return false;
}
I can't deal with this. Please help me. This is array:
$arr = array("data" => array(
array("id" => "5451"),
array("id" => "45346346")
));
for example how can i find the key for id 45346346 ?
$key = array_search($arr['data'], 45346346);
I have tried this but its not working.
I'm trying to delete that array line. I'm guessing I can do that with unset($key)
You have an array of array of arrays. $arr['data'] is an array with 2 values. These values are both arrays. array_search doesn't work, as 45346346 doesn't match an array.
You'd have you cook your own search, something like this:
function find_in_array($arr, $val){
$found = false;
foreach($arr as $k=>$x){
if(array_search($val, $x) !== FALSE){
$found = $k;
break;
}
}
return $found;
}
Then you can do: $key = find_in_array($arr['data'], 45346346);. This will return 1, the index of the array containing 'id' => 45346346 inside $arr['data'].
DEMO: http://codepad.org/pSxaBT9g