I have a simple PHP array inside an array which looks like this:
$defaults = array(
"color" => "White",
array(
"color" => "0000CC",
)
)
The problem becomes when I want to call the second color item--since they are both named the same, I can't figure out how to access the SECOND color item on the command line. This command line code below doesn't work because it only gets the FIRST color item in the first array.
php /Users/me/temp/the_Script/create.php --color='0000CC'
How do I access that SECOND color item in the second array on the command line? Can I even grab both of them in the same command line arguments?
Thanks!
You can access like this:
$defaults[0]["color"]
This is because when you create an associative array they don't have index number, so when you create the second array inside the defaults array, PHP assign that to the first position.
In this particular case
$defaults = array( "color" => "White", array( "color" => "0000CC", ) );
var_dump($defaults[0]['color']);
But you're better off giving it an association
$defaults = array( "color" => "White", "codes" => array( "color" => "0000CC", ) );
var_dump($defaults['codes']['color']);
The general structure of your array doesn't make any sense to me though. I don't know if that's because you're just using it as an example or if you need to rethink the structure.
Related
I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.
$arrImages[] =
[
'img_sm'=>'image1.jpg',
'tag_GlassDoor'=>0,
'tag_GlassWall'=>1,
];
$arrImages[] =
[
'img_sm'=>'image2.jpg',
'tag_GlassDoor'=>1,
'tag_GlassWall'=>1,
];
Filtering is the answer, it can be used to filter one dimensional Arrays and multidimensional arrays.
the general implementation would be something like this:
$arr = array(
array(
'image' => "data",
'hasObject' => 1
),
array(
'image' => "data",
'hasObject' => 0
),
);
$finteredArray = array_filter($arr, function ($r) {
return (bool) $r['hasObject'];
});
print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )
This question already has an answer here:
array_push won't give an array, prints out integer value
(1 answer)
Closed 4 years ago.
I've attempted many different ways to push an array into a multidimensional array, including array_push(), $array['index'] = $toPush but I keep being met with quite unexpected results. I have used both var_dump() and print_r() as detailed below in an attempt to debug, but cannot work out the issue.
My reasoning behind is to run a while loop to pull game id's and game names and store these in an assoc. array, and then push them into my main array.
$games_array = array
(
"games" => array
(
array("id"=>"1", "game"=>"first game");
array("id"=>"2", "game"=>"second game");
)
);
// a while loop would run here and update $game_to_add;
$game_to_add = array("id"=>"$game['id']", "game"=>"$game['title']");
$games_array = array_push($games_array['games'], $game_to_add);
In this example, the while() would update the ID and the Game inside of $game_to_add
But, whenever I attempt this it simply overwrites the array and outputs an integer ( example: int(3) )
I don't understand what the problem is, any explination would be appreciated as I cannot find a question specifically for this.
My actual test code:
$games_array = array( "games" => array(
array("id" => "1", "name" => "Star feathers"),
array("id" => "2", "name" => "chung fu")
)
);
$another_game = array("id" => "3", "name" => "some kunt");
$games_array = array_push($games_array["games"], array("id" => "3", "name"
=>"some game"));
var_dump($games_array);
You're assigning the return value of array_push to the games array.
The return value of array_push is the amount of elements after pushing.
Just use it as
array_push($array, $newElement);
(Without assignment)
If you're only pushing one element at he time, $array[] = $newElement is preferred to prevent overhead of the function call of array_push
I have a Master PHP array at the bottom of my question. It all works as it should and encodes to json perfectly. My problem is confined to the "content" object shown in the array.
The 'content' object should contain up to ten sub-arrays ($newSubArray0-9)each sub-array being populated with image data according to this simple loop below (the data is all available from a prior database query - so no issues there).
//get data for the 'content' object sub arrays....
for( $i = 0; $i<9; $i++ ) {
$newSubArray.$i =
[
'url' => $uploadspath.$media_url.$i,//main image
"type" =>$type.$i,//media type
"caption"=>$caption.$i
];
}
Now...in the master array below I simply need to be able to exclude or delete any of the $newSubArray (0-9) instances IF its corresponding media-condition yields an empty media result ie (!media_url.$i) or ($media_url.$i="").
I have tried...
If (media-conditon)
...{$newSubArray.$i=UNSET($newSubArray.$i);}
...{$newSubArray.$i=array_filter($newSubArray.$i);}
...{$newSubArray.$i=array_values($newSubArray.$i);}
All of these attempts affect the subarray elements I am trying to delete entirely (based on the condition) BUT leave a trace of the subarray itself eg 'none'. That trace causes the subsequent data validation to fail. The vailidation is being done by a third party API to which the json data is sent--so I cannot change the validation. I need there to be absolutely NO record of any subarray for which there is no associated $media_url value.
Here is a portion of the Master Array with the sub array elements that I need to conditionally include or exclude depending on the availability of associated images. It all works fine ...just need to solve the problem above.
$data = json_encode
(
array
(
"location" =>array
(
"property_number_or_name" => $house_name_number,
"street_name" => $propaddress1,
"locality" => $propaddress2,
"town_or_city" => $town,
"postal_code" => $postcode,
"country_code" => "GB",
"coordinates"=>array
(
"latitude"=>(float)$latitude,
"longitude"=>(float)$longitude
)
),
"pricing" =>array
(
"rent_frequency" => $rent_frequency,
"currency_code" => "GBP",
"price" => (int)$price,
"transaction_type" => "rent"
),
"detailed_description" =>array
(
array
(
"text" => $description
)
),
"content" => array
(
$newSubArray0,//remove this sub array completely if no media_url0
$newSubArray1,//remove this sub array completely if no media_url1
$newSubArray2,//remove this sub array completely if no media_url2
$newSubArray3,//remove this sub array completely if no media_url3
$newSubArray4,//remove this sub array completely if no media_url4
$newSubArray5,//remove this sub array completely if no media_url5
$newSubArray6,//remove this sub array completely if no media_url6
$newSubArray7,//remove this sub array completely if no media_url7
$newSubArray8,//remove this sub array completely if no media_url8
$newSubArray9 //remove this sub array completely if no media_url9
),
"google_street_view"=>array
(
"heading"=>(float)$pov_heading,
"pitch"=> (float)$pov_pitch,
"coordinates"=> array
(
"latitude"=>(float)$pov_latitude,
"longitude"=>(float)$pov_longitude
)
),
"display_address"=> $display_address,
"summary_description"=> $summary
,JSON_UNESCAPED_SLASHES);
You likely want unset but to not store the result of the call in the same place.
Yours:
If (media-conditon)
...{$newSubArray.$i=UNSET($newSubArray.$i);}
Update:
If (media-conditon)
...{UNSET($newSubArray.$i);}
You could also do this more efficiently by validating your media condition before you set the element in the content data.
So I am writing something to add on to my website.
I have this value stated above:
$settings[] = array(
"name" => "torblock_redirecturl",
"title" => $lang->redirecturl,
"optionscode" => "text",
"disporder" => 1,
"value" => denied.php,
"gid" => $gid
There will be a setting that where someone can enter another url or page. But I have this later in the php file:
die('$torblock_redirecturl');
I want that to change to the value in the setting once the setting is changed.
Aka once a value is entered in the setting, I want the value to change to whatever was entered right in the die.
Thanks for your answers!
You were assigning multidimensional array.
$settings[] = array( "value" => denied.php);
So to get the value access like $settings[0]['value']; the index 0 changes according to number of arrays stored in the $settings
To get expected
die($settings[0]['value']);
Update :
If assigning as single dimensional array.
$settings = array( "value" => denied.php);
Then access it like die($settings['value']);
Try this:
die($settings[0]['name']);
It would be easier to help if you supplied more context, but your syntax error could imply that you wrap an array variable in quotes without escaping, like so:
die('$settings['name']'); // this will break
If you prefer wrapping variables in quotes, you can do it like so:
die("{$settings[0]['name']}");
You may be aware of this, but in your code you're not just assigning an array to the $settings variable:
// this:
$settings[] = array('name' => 'foo');
// is the same as doing this:
$settings = array();
array_push($settings, array('name' => 'foo'));
I have a multidimensional associative array that is made of of animals:
$animals = ["Cat"=>["name"=>"Junior","age"=>16],"Dog"=>["name"=>"Puppy","age"=>"Deceased"]];
I want to add a new animal to it. I know I can do this:
$animals["Lizard"]["name"]="Allen";
$animals["Lizard"]["age"]="Deceased";
But is there a way to do in in one statement, such as
$animals["Lizard"](["name"]="Eric",["age"]=>"Deceased");
Sorry I know this is a really dumb question but I'm a beginner. Thanks.
Just add entire array as an element:
$animals["Lizard"] = [ "name" => "Eric", "age" => "Deceased" ];
or
$animals["Lizard"] = array( "name" => "Eric", "age" => "Deceased" );
Manual (look at example #6).