Inserting Values into Array - php

I Select * From my sql table in PHP, and I convert it to JSON, so the results are like this:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla"},
{"id":"351","Name":"BlaBla","Info":"BlaBla"},
{"id":"352","Name":"BlaBla","Info":"BlaBla"}
]);
I scrape a clients website for images (this is a request of the client) based on the id in the records above, and I output images into a similar array/dictionary and output into JSON:
([
{"image1":"http://Sourceofimg.jpg"},
{"image2":"http://Sourceofimg.jpg"},
{"image3":"http://Sourceofimg.jpg"},
{"image4":"http://Sourceofimg.jpg"},
{"image5":"http://Sourceofimg.jpg"}
]);
So lets say I scrape a page, page.php?id=350, I'd get a similar output to the image array above, how can I append/add that result to the first array where id=350?
EDIT
This is where I would like to combine the arrays:
while ($row = mysql_fetch_assoc($results))
{
$rows[] = $row;
$url = 'http://www.url.com/page.php?id='.$row['id'].'';
$html = file_get_html($url);
foreach($html->find('div.classvalue') as $element){
foreach($element->find('img') as $img){
$images[] = array("image".$i."" => $img->src);
$i = $i + 1;
$rows = array_merge($rows, $images);
} } }
My version clearly does not work, it seems to be appending new images to the already existing image[] therefore the last element of $rows[] will get the full list of images, where I just want the images tied in with that id.
Also by merging, it does not merge correctly I get an output like this e.g:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla"},
{"image1":"http://Sourceofimg.jpg"},
{"image2":"http://Sourceofimg.jpg"},
{"id":"351","Name":"BlaBla","Info":"BlaBla"}
]);
I would like it like:
([
{"id":"350","Name":"BlaBla","Info":"BlaBla", "image1":"http://Sourceofimg.jpg", "image2":"http://Sourceofimg.jpg"} etc...
]);

I think this is what you need. You first have to start with a clean $images array using $images = array(); so you won't have the results of previous loops in your array. Then you should collect the images inside the $images array (using the forloops). Then you can store the images in the $row array under the key 'images' using $row['images'] = $images;.
Hope this is what you need.
while ($row = mysql_fetch_assoc($results)) {
$url = 'http://www.url.com/page.php?id='.$row['id'].'';
$html = file_get_html($url);
$images = array();
$i = 0;
foreach($html->find('div.classvalue') as $element){
foreach($element->find('img') as $img){
$row["image".$i] = $img->src;
$i = $i + 1;
}
}
$rows[] = $row;
}

On php side use array_merge() with both arrays. In addition array_unique will become handy (it will remove duplicates).

You have to add $images to the actual row. What you are doing, is resizing array.
$actualIndex = count($rows);
$rows[] = $row;
...
...
$rows[$actualIndex] = $images;
Or something like this
You can tweak $rows[$actualIndex] to satisfy your structure.
First set somewhere $imageID = 1;
$rows[$actualIndex]['image'.$imageID] = $images['url']
imageID++;

Related

want to convert a key value pair to standard class object

Hi I need help [this is my table structure] and my current [JSON response is like this] and I want to convert this to [like this JSON response]
Can anybody give some idea or any related code so that I can make my JSON response like that.
*Note I can't create another table to store user images
First you don't need to concatenate your base_url to all images, you can use it separately in your front file, unless it must be there.
Second you don't need to store user_id to your image structure, because you have id right in your table's structure.
anyway you can do something like snippet below.
I hope it works fine :)
Edit:
It is easier to work with arrays in PHP so I convert my code to array version and if you need to use object first convert your object to array and after snippet you can convert it to object like (object) $data
foreach ($data as &$user) {
if(!empty($user['main_image'])) {
$user['main_image'] = $image_basepath . $user['main_image'];
}
$user['image'] = [];
for($i = 1; $i <= 6; $i++) {
$imgArr = [];
$img = $user['optnl_img' . $i];
unset($user['optnl_img' . $i]);
if(isset($img) && !empty($img)) {
$imgArr['id'] = $i;
$imgArr['user_id'] = $user['id'];
$imgArr['image'] = $image_basepath . $img;
}
$user['image'][] = $imgArr;
}
}

php create arrays dynamically and merge

I'm trying to create an unknown number of arrays dynamically inside a foreach loop, merge them all at the end into one array, and use this in a JSON format for Google Analytics.
So far I have the following code which is throwing an error at the merge part:
$p=1;
foreach(...){
...
$arr = 'arr'.$p;
$name = $order->ProductGroupName;
$name = str_replace("'", "", $name);
$arr = array(
"name"=>$name,
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
for ($q = 1; $q<$p; $q++){
$arry = 'arr'.$q;
$merge = array_merge($arry, $merge);
};
How do I create the arrays dynamically and merge them at the end, please?
I'm relatively new to PHP and have tried my best to get this to work.
I think I understand what you're trying to do. Just dynamically append [] to the array and you don't need to merge:
foreach($something as $order) {
$arr[] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
}
If you want to have string keys for whatever reason, then:
$p = 1;
foreach($something as $order) {
$arr["SomeText$p"] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
And that's it. Check with:
print_r($arr);
Things like $arry = 'arr'.$q; stink of variable variables (though not done correctly) and shouldn't be used.

Grab rows and then cells from a table

I'm using the Simple HTML Dom Parser to grab a table (in the image) and then grab each tr. This outputs all the items in the row as one string.
$contents = $html->find('div[class=product-table]', 0);
$titles = $contents->find('tr');
How can I create an array that keeps the data in rows but also allows me to output the individual cells? I want to be able to say there's 7 cells in a row (this could be flexible) and be able to output each individual cell in the row as variables (I need to do other stuff with these).
// Product Code Titles
$contents = $html->find('div[class=product-table]', 0);
$data = array();
$rows = $contents->find('tr');
$counter = 1;
foreach ($rows as $key_row => $row) {
// process rows here
foreach ($row->find('td') as $key_cell => $cell) {
$field_key = "field_5ae0882f9d6f9";
$data[] = array(
"column_title" => strip_tags($cell->innertext),
);
$counter++;
// process each cell on the current row iteration
// or whatever you need to do in each cell (calculations and whatnot)
// $data[] = then push it inside an array (you can prolly use the keys and use it in `$data`)
}
} ?>
<pre>
<?php print_r($data); ?>
</pre>
<?php update_field( $field_key, $data, $post_id );
Just like what I've said in the comments, treat the first loop for the rows, and for each row, another foreach for each cell. So basically you need two.
There's not much to go on since you don't have a sample markup, but here's the idea:
$data = array();
$rows = $contents->find('tr');
foreach ($rows as $key_row => $row) {
// process rows here
foreach ($row->find('td') as $key_cell => $cell) {
// process each cell on the current row iteration
echo $cell->innertext;
// or whatever you need to do in each cell (calculations and whatnot)
// $data[] = then push it inside an array (you can prolly use the keys and use it in `$data`)
}
}
Sidenote: Take note, if you want the header to be skipped, just use a counter and an if condition with continue, then you're good to go.

PHP Echo XML Attributes Without Repeating

my question has to do with PHP and XML. I would like to echo out some attributes, but echo ones that repeat only once.
Say this was the XML I was dealing with, and it was called beatles.xml:
<XML_DATA item=“TheBeatles”>
<Beatles>
<Beatle Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Beatle>
<Beatle Firstname=“John” Lastname=“Lennon” Instrument=“Guitar”>Lennon, John</Beatle>
<Beatle Firstname=“Paul” Lastname=“McCartney” Instrument=“Bass”>McCartney, Paul</Beatle>
<Beatle Firstname=“Ringo” Lastname=“Starr” Instrument=“Drums”>Starr, Ringo</Beatle>
</Beatles>
</XML_DATA>
This is the PHP I have so far:
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
foreach($beatles as $beatle) {
echo $beatle->attributes()->Instrument.',';
}
I would expect this to echo out Guitar,Guitar,Bass,Drums, but I would like Guitar to only display once. How would I prevent repeat attribute values from echoing out?
Inside the foreach loop, cast the instrument name as a string and push it into an array. Once the loop finishes execution, you will have an array containing all the instrument names (with duplicates, of course). You can now use array_unique() to filter out the duplicate values from the array:
$instruments = array();
foreach($beatles as $beatle) {
$instruments[] = (string) $beatle->attributes()->Instrument;
}
$instruments = array_unique($instruments);
Demo.
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
$result = array();
foreach($beatles as $beatle) {
if (!array_key_exists($beatle->attributes()->Instrument, $result)) {
$result[] = $beatle->attributes()->Instrument;
// echo $beatle->attributes()->Instrument.',';
}
}
then Loop through the $result array with foreach
Either use xpath.

Adding to an associative array PHP

I have an array with three indexes which themselves are arrays:
$array['title'];
$array['description'];
$array['link'];
I need to add to this array in a loop.
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array = $information['processed'];
}
The above works fine when I do it once without the loop, however I cannot add to $array.
What I have tried is:
$array = array();
$arraytemp = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$arraytemp = $information['processed'];
$array = $array + $arraytemp; // the unique append as outlined in php manual
}
I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[] = $information['processed'];
}
And I have also tried:
$array = array();
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
array_push($array,$information['processed']);
}
For the application I am developing, I need a way of adding to this array whilst reserving the key structure. So I want to add the new information to the end of the array.
Creating a new dimension by doing something like the following is not appropriate for my program:
for ($i=0;$i<10;$i++)
{
// information is processed, different information on each loop
$array[$i] = $information['processed'];
}
//The above is not appropriate for my application
Any ideas?
Thanks guys.
$array = array();
for ($i=0;$i<10;$i++)
{
$array[$i] = $information['processed'];
}

Categories