PHP: How do I echo the results of this array? - php

$header_content = array();
$header_content['pageone'][] = array(
'image' => 'photo-one.png',
'desc' => "One. Some text here.",
);
$header_content['pagetwo'][] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
I do not want to echo the entire array, just certain parts when called... like $header_content['pageone']['image'], except this doesn't work... How do you go about echoing parts of an array?
I have searched but it's all a little confusing right now for me. Thanks.

Define it like -
$header_content['pagetwo'] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
The keys are different pageone, pagetwo. No need of that extra index i think. And then access it - echo $header_dontent['pagetwo']['image'];

For printing array values, you can use :
print_r function
Example : print_r($array)
Specific key data can be accessed through : print_r($array[$key])
OR
var_dump function
Example : var_dump($array)
Specific key data can be accessed through : var_dump($array[$key])

use it like $header_content['pageone'][0]['image']
Since
$header_content['pageone'][] = array();
[] appends an element at the end of an array.

Related

Trying to add an array to an associated array

I have an associated array saved in my database that Im saving to a variable called response_cost using the Wordpress function get_post_meta.
$response_cost = get_post_meta( $postID, $metaKey, true );
The array looks something like this:
a:2: {
i:0;a:3:
{s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
i:1;a:3:
{s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
}
I have a form that I've created which outputs a new array and it's saved in a variable called $add_to_response_cost.
$add_to_response_cost = array (
'type' => $type,
'cost' => $cost,
'modifyer' => $modifyer
);
I'm can't figure out how to add $add_to_response_cost as another instance of $response_cost so that the out put ends up like so:
a:3: {
i:0;a:3:
{s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
i:1;a:3:
{s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
i:2;a:3:
{ my new array I've constructed via $add_to_response_cost }
}
Any help or direction with this is greatly appreciated.
To understand the problem, first we need to explain a little about how saving arrays in custom fields works
Here we have an array
$array = array(
"0" => array(
"type" => "months",
"cost" => null,
"modifier" => "=",
),
"1" => array(
"type" => "weeks",
"cost" => null,
"modifier" => "+",
)
);
If we decide to save it as a custom field in the database, we use the update_post_meta() function
update_post_meta( 1, 'response_cost', $array );
Before saving it to the database, Wordpress will serialize our array and then put it into the database.
As a result, the array will be saved in the database in the following format
a:2:{i:0;a:3:{s:4:"type";s:6:"months";s:4:"cost";N;s:8:"modifier";s:1:"=";}i:1;a:3:{s:4:"type";s:5:"weeks";s:4:"cost";N;s:8:"modifier";s:1:"+";}}
Then, if we want to get an array, we use get_post_meta()
$myarray = get_post_meta(1, "response_cost", true);
Wordpress will take a serialized array from the database and convert it to a typical array.
Then we can add any data we want to the array and save it back to the database.
$add_to_response_cost = array (
'type' => $type,
'cost' => $cost,
'modifyer' => $modifyer
);
$myarray[] = $add_to_response_cost;
update_post_meta( 1, 'response_cost', $myarray );
Usually this problem occurs when using the get_post_meta function without specifying a key, with only one parameter (ID), then we get arrays without processing and they must first be unserialized
This can also happen when you get an array from a database not through a Wordpress function, but by direct SQL query to the database.
Then you need to unserialize the array first, add data to it and pack it back.
You can try unserialize() to convert it to array.
$result = unserialize($response_cost);
Print_r($result);

Rewrite 2d array, which contains only some keys

I am using Animate.css for Bootstrap carousel and I need to sort the animations.
I have made an array called $anims, which contains all the animations. I want to make a new variable which contains only entrance animations, for example. So this is my array.
$anims = array(
"Bouncing Entrances" => array(
"bounceIn",
"bounceInDown",
....
),
"Bouncing Exits" => array(
"bounceOut",
"bounceOutDown",
....
),
"Fading Entrances" => array(
"fadeIn",
"fadeInDown",
....
),
......
)
$enrtyAnims = ...
?>
After processing it should look like that:
$anims = array(
"Bouncing Entrances" => array(
"bounceIn",
"bounceInDown",
....
),
"Fading Entrances" => array(
"fadeIn",
....
)
)
But I don't have any idea how to do it with the keys. I want to be able to say I want new array with keys X and Y and it makes it.
You can simply use array_filter function with third flag parameter along with the flag ARRAY_FILTER_USE_KEY so your code looks like as
$result_array = array_filter($anims,function($k){
return (strpos($k,"Entrances") !== false);
},ARRAY_FILTER_USE_KEY);
Note: Flags as third parameter are introduced in PHP versions >= 5.6.0
Demo
Access the desired elements by key and create a new array using these items, like this:
$anims = array(
'Bouncing Entrances' => $anims['Bouncing Entrances'],
'Fading Entrances' => $anims['Fading Entrances'],
// ...
);
EDIT: forgot to preserve the keys.
If there's a certain pattern by which you want to filter the animations, you can use array_filter() function, like #Uchiha said.

pushing and apending arrays into an associative array in php

How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);

how to refer to the text value?

$list_box_contents = array();
$list_box_contents[0] = array('params' => 'class="productListing-odd"');
$list_box_contents[0][] = array('params' => 'class="productListing-data"',
'text' => TEXT_NO_PRODUCTS);
i want to make a condition whether there is a value in $list_box_contents[0][]["text"] .when i write the code if(!empty($list_box_contents[0][]["text"])). my IDE alet me there is an error. what's wrong with it?
[] it's not a position, index or something like this.
With
$list_box_contents[0][] = array('params' => 'class="productListing-data"',
'text' => TEXT_NO_PRODUCTS);
you are pushing the array with its two value (and keys) on the right of the = in the last position of the subarray which has index 0. That is the structure you'll have is:
$list_box_contents[0] => array(VALUES-BEFORE, [last-position-key] => array('params' => 'class="productListing-data"', 'text' => TEXT_NO_PRODUCTS))
Anyway to have an idea of what happens, you can use print_r($list_box_contents) or var_dump($list_box_contents)
after the lines you posted.
When you assign something as in $list_box_contents[0][], you are assigning the contents of whatever follows to the next element in the array $list_box_contents[0]. So in this case, you would be assigning
array('params' => 'class="productListing-data"',
'text' => TEXT_NO_PRODUCTS);
to index 0 of $list_box_contents[0].
You can't refer to it using the $array[] notation, because the PHP parser doesn't have any idea which element in $array that you want to refer to. You need to specify.

Replace array key integers with string

$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1

Categories