PHP How to Unset Member of Multidimensional Array? - php

I have a three dimensional array that looks like this
Array(
[Group 1] => Array
(
[0] => Array
(
[category] => Group1
[firstname] => John
[lastname] => Johns
[image] => /mysite.etc/jj.jpg
)
[1] => Array
(
[category] => Group1
[firstname] => John
[lastname] => James
[image] => /mysite.etc/jj2.jpg
)
)
[Group 2] => Array
(
[0] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jackson
[image] => NULL
)
[1] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jimson
[image] => /mysite.etc/jj4.jpg
)
)...etc)
I'm trying to loop through the array and remove any people (i.e. the second level of the array) who do not have a value in the [image] cell.
I've tried
foreach($MyArray as $Key=>&$group){
foreach($group as &$staff){
if(!file_exists($staff['image'])){
unset($staff);
}
}
}
but this does not remove the array items with no image. The loop is correctly identifying the staff with no image as if I include a bit of code to echo them onto the page, this works. It's just not unsetting them from the $MyArray array.
Can anyone help me achieve this?

foreach($MyArray as $Key=>$group){
foreach($group as $k=>$staff){
if( !file_exists($staff['image'])) {
unset($MyArray[$Key][$k]);
}
}
}
//you should know the the $group and $staff is temp variables

foreach ($MyArray as $Key=>$group) {
foreach ($group as $k=>$staff) {
if( empty($staff['image']) || !file_exists($staff['image'])) {
unset($MyArray[$key][$k]);
}
}
}

The condition should be following like this.
foreach($MyArray as $Key=>&$group){
foreach($group as $staffkey=>$staff){
if( $staff['image'] == null))
{
unset($MyArray[$key][$staffkey]);
}
}
}

You can use array_filter for this:
With a closure: available in php 5.3
foreach($groups as &$users){
$users = array_filter($users, function ($a) { return isset($a["image"]) && file_exists($a["image"]); });
}
Without closures
function hasImage($a){ return isset($a["image"]) && file_exists($a["image"]); }
foreach($groups as &$users){
$users = array_filter($users, "hasImage");
}

Related

Delete array from nested array

How can I delete the first Name arrray
[0] => Array
(
[Name] => John
)
from this one just if exist at lest two Name objects?
Array
(
[0] => Array
(
[Name] => John
)
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Surname] => Doe
)
)
I'm trying to go through array with foreach, count how many arrays has name object and if there is more than one, then unset the first, but I'm not able to do that:
foreach($endArray as $arr)
{
if(count($arr['Name'])>1)
{
unset($endArray[0]);
}
}
In your code you use if(count($arr['Name'])>1) but I think that will never be true as the count will return 1 when the value is neither an array nor an object with implemented Countable interface.
To unset the first when there are more than one, you could count the number of occurrences of "Name" in the items using array_column.
If you want to remove the first array which has a key "Name" you could loop over the items and use unset using the $key.
Then break the loop to only remove the first encounter item.
$endArray = [
["Name" => "John"],
["Name" => "James"],
["Name" => "Doe"]
];
if (count(array_column($endArray, 'Name')) > 1) {
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr)) {
unset($endArray[$key]);
break;
}
}
}
print_r($endArray);
Php demo
Output
Array
(
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Name] => Doe
)
)
Another option is to keep track of the number of times the "Name" has been encountered:
$count = 0;
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr) && $count === 0) {
$count++;
} else {
unset($endArray[$key]);
break;
}
}
Php demo

How to insert item on every item in an array using PHP

I have this existing array
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
)
)
I want to insert new item in each array like [randomNumber] => 50. So the final output must be like this
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
[randomNumber] => 25
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
[randomNumber] => 50
)
)
I'm using php using for loop to insert the randomNumber every user
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i] = array('randomNumber' => rand(10,100));
}
It doesn't seems to work. What should be the proper way? Thanks
Iterate with a foreach, and as $user is an object, it will be passed to loop by reference:
foreach ($users as $user) {
$user->randomNumber = rand(10,100);
}
As you have an array of objects rather than arrays...
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i]->randomNumber = rand(10,100);
}
I think foreach function is better for you. and you have array of objects.
foreach ($users as $key => $value) {
$users[$key]->randomNumber = rand(10,100);
}

Taking out just one value from an array

I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>

Taking values from Arrays inside an array

Below is the display of my array $arr[0]. Could you please tell me how to take the values of inner array?
Here I need to take only the value for the ID 656 which is 'John'.
Array
(
[0] => xxxxxxxxx
(
[Users] => Array
(
[0] => Array
(
[name] => 656
[value] => John
)
[1] => Array
(
[name] => 657
[value] =>Peter
)
[2] => Array
(
[name] => 658
[value] => Louie
)
[3] => Array
(
[name] => 659
[value] => Jim
)
)
)
Thanks in advance.
try running a:
foreach($arr as $key=>$value){
var_dump($value);
}
And you'll probably be able to work out what to do from there. Hope that helps?
EDIT: if
$arr = array(
0=>array(
'Users'=>array(
0=>array('name'=>656, 'value'=>'John'),
1=>array('name'=>656, 'value'=>'John'),
2=>array('name'=>658, 'value'=>'Louie')
)
)
);
Then you can use:
foreach($arr as $Users){
foreach($Users as $k=>$v){
var_dump($v[0]['value']);
}
}
To get 'John'. Does that help?
If this isn't just a one-off, you could use a recursive array search function. If your data is in $arr, in the format you described:
$arr = array(array("Users"=>array(array("name"=>656,"value"=>"John"),array("name"=>657,"value"=>"Peter"))));
It might look like this:
print in_array_multi("656",$arr);
// ^-- This prints John
print in_array_multi("657",$arr);
// ^-- This prints Peter
function in_array_multi($item, $arr) {
foreach ($arr as $key => $value) {
if ($value==$item){
return $arr['value'];
} else if (is_array($value)){
if($ret = in_array_multi($item, $value))
return $ret;
}
}
return "";
}
for example:
i supose you have 3 arrays to arrive where you wanna ok?
array_1[0].array_2[0].array_3[0]---> here you the information you need.
so you have 2 arrays inside array_1 at position 0.
for(){//to watch the first array all positions
for(){//top watch the second array idem
for(){//to watch the 3 idem...
here at teh position 0 take away the values...
}
}
}
it hope it helps.

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories